repo
stringlengths
6
65
file_url
stringlengths
81
311
file_path
stringlengths
6
227
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 15:31:58
2026-01-04 20:25:31
truncated
bool
2 classes
linera-io/linera-protocol
https://github.com/linera-io/linera-protocol/blob/69f159d2106f7fc70870ce70074c55850bf1303b/examples/fungible/src/contract.rs
examples/fungible/src/contract.rs
// Copyright (c) Zefchain Labs, Inc. // SPDX-License-Identifier: Apache-2.0 #![cfg_attr(target_arch = "wasm32", no_main)] mod state; use fungible::{ FungibleOperation, FungibleResponse, FungibleTokenAbi, InitialState, Message, Parameters, }; use linera_sdk::{ linera_base_types::{Account, AccountOwner, Amount, WithContractAbi}, views::{RootView, View}, Contract, ContractRuntime, }; use self::state::FungibleTokenState; pub struct FungibleTokenContract { state: FungibleTokenState, runtime: ContractRuntime<Self>, } linera_sdk::contract!(FungibleTokenContract); impl WithContractAbi for FungibleTokenContract { type Abi = FungibleTokenAbi; } impl Contract for FungibleTokenContract { type Message = Message; type Parameters = Parameters; type InstantiationArgument = InitialState; type EventValue = (); async fn load(runtime: ContractRuntime<Self>) -> Self { let state = FungibleTokenState::load(runtime.root_view_storage_context()) .await .expect("Failed to load state"); FungibleTokenContract { state, runtime } } async fn instantiate(&mut self, state: Self::InstantiationArgument) { // Validate that the application parameters were configured correctly. let _ = self.runtime.application_parameters(); let mut total_supply = Amount::ZERO; for value in state.accounts.values() { total_supply.saturating_add_assign(*value); } if total_supply == Amount::ZERO { panic!("The total supply is zero, therefore we cannot instantiate the contract"); } self.state.initialize_accounts(state).await; } async fn execute_operation(&mut self, operation: Self::Operation) -> Self::Response { match operation { FungibleOperation::Balance { owner } => { let balance = self.state.balance_or_default(&owner).await; FungibleResponse::Balance(balance) } FungibleOperation::TickerSymbol => { let params = self.runtime.application_parameters(); FungibleResponse::TickerSymbol(params.ticker_symbol) } FungibleOperation::Approve { owner, spender, allowance, } => { self.runtime .check_account_permission(owner) .expect("Permission for Transfer operation"); self.state.approve(owner, spender, allowance).await; FungibleResponse::Ok } FungibleOperation::Transfer { owner, amount, target_account, } => { self.runtime .check_account_permission(owner) .expect("Permission for Transfer operation"); self.state.debit(owner, amount).await; self.finish_transfer_to_account(amount, target_account, owner) .await; FungibleResponse::Ok } FungibleOperation::TransferFrom { owner, spender, amount, target_account, } => { self.runtime .check_account_permission(spender) .expect("Permission for Transfer operation"); self.state .debit_for_transfer_from(owner, spender, amount) .await; self.finish_transfer_to_account(amount, target_account, owner) .await; FungibleResponse::Ok } FungibleOperation::Claim { source_account, amount, target_account, } => { self.runtime .check_account_permission(source_account.owner) .expect("Permission for Claim operation"); self.claim(source_account, amount, target_account).await; FungibleResponse::Ok } } } async fn execute_message(&mut self, message: Message) { match message { Message::Credit { amount, target, source, } => { let is_bouncing = self .runtime .message_is_bouncing() .expect("Message delivery status has to be available when executing a message"); let receiver = if is_bouncing { source } else { target }; self.state.credit(receiver, amount).await; } Message::Withdraw { owner, amount, target_account, } => { self.runtime .check_account_permission(owner) .expect("Permission for Withdraw message"); self.state.debit(owner, amount).await; self.finish_transfer_to_account(amount, target_account, owner) .await; } } } async fn store(mut self) { self.state.save().await.expect("Failed to save state"); } } impl FungibleTokenContract { async fn claim(&mut self, source_account: Account, amount: Amount, target_account: Account) { if source_account.chain_id == self.runtime.chain_id() { self.state.debit(source_account.owner, amount).await; self.finish_transfer_to_account(amount, target_account, source_account.owner) .await; } else { let message = Message::Withdraw { owner: source_account.owner, amount, target_account, }; self.runtime .prepare_message(message) .with_authentication() .send_to(source_account.chain_id); } } /// Executes the final step of a transfer where the tokens are sent to the destination. async fn finish_transfer_to_account( &mut self, amount: Amount, target_account: Account, source: AccountOwner, ) { if target_account.chain_id == self.runtime.chain_id() { self.state.credit(target_account.owner, amount).await; } else { let message = Message::Credit { target: target_account.owner, amount, source, }; self.runtime .prepare_message(message) .with_authentication() .with_tracking() .send_to(target_account.chain_id); } } }
rust
Apache-2.0
69f159d2106f7fc70870ce70074c55850bf1303b
2026-01-04T15:33:08.660695Z
false
linera-io/linera-protocol
https://github.com/linera-io/linera-protocol/blob/69f159d2106f7fc70870ce70074c55850bf1303b/examples/fungible/src/lib.rs
examples/fungible/src/lib.rs
// Copyright (c) Zefchain Labs, Inc. // SPDX-License-Identifier: Apache-2.0 /* ABI of the Fungible Token Example Application */ use async_graphql::scalar; pub use linera_sdk::abis::fungible::*; use linera_sdk::linera_base_types::{Account, AccountOwner, Amount}; use serde::{Deserialize, Serialize}; #[cfg(all(any(test, feature = "test"), not(target_arch = "wasm32")))] use { async_graphql::InputType, futures::{stream, StreamExt}, linera_sdk::{ linera_base_types::{ApplicationId, ModuleId}, test::{ActiveChain, QueryOutcome, TestValidator}, }, }; /// A message. #[derive(Debug, Deserialize, Serialize)] pub enum Message { /// Credits the given `target` account, unless the message is bouncing, in which case /// `source` is credited instead. Credit { /// Target account to credit amount to target: AccountOwner, /// Amount to be credited amount: Amount, /// Source account to remove amount from source: AccountOwner, }, /// Withdraws from the given account and starts a transfer to the target account. Withdraw { /// Account to withdraw from owner: AccountOwner, /// Amount to be withdrawn amount: Amount, /// Target account to transfer amount to target_account: Account, }, } #[derive(Clone, Debug, Deserialize, Serialize)] pub struct OwnerSpender { /// Account to withdraw from pub owner: AccountOwner, /// Account to do the withdrawing pub spender: AccountOwner, } scalar!(OwnerSpender); impl OwnerSpender { pub fn new(owner: AccountOwner, spender: AccountOwner) -> Self { if owner == spender { panic!("owner should be different from spender"); } Self { owner, spender } } } /// Creates a fungible token application and distributes `initial_amounts` to new individual /// chains. #[cfg(all(any(test, feature = "test"), not(target_arch = "wasm32")))] pub async fn create_with_accounts( validator: &TestValidator, module_id: ModuleId<FungibleTokenAbi, Parameters, InitialState>, initial_amounts: impl IntoIterator<Item = Amount>, ) -> ( ApplicationId<FungibleTokenAbi>, Vec<(ActiveChain, AccountOwner, Amount)>, ) { let mut token_chain = validator.new_chain().await; let mut initial_state = InitialStateBuilder::default(); let accounts = stream::iter(initial_amounts) .then(|initial_amount| async move { let chain = validator.new_chain().await; let account = AccountOwner::from(chain.public_key()); (chain, account, initial_amount) }) .collect::<Vec<_>>() .await; for (_chain, account, initial_amount) in &accounts { initial_state = initial_state.with_account(*account, *initial_amount); } let params = Parameters::new("FUN"); let application_id = token_chain .create_application(module_id, params, initial_state.build(), vec![]) .await; for (chain, account, initial_amount) in &accounts { let claim_certificate = chain .add_block(|block| { block.with_operation( application_id, FungibleOperation::Claim { source_account: Account { chain_id: token_chain.id(), owner: *account, }, amount: *initial_amount, target_account: Account { chain_id: chain.id(), owner: *account, }, }, ); }) .await; assert_eq!(claim_certificate.outgoing_message_count(), 1); let transfer_certificate = token_chain .add_block(|block| { block.with_messages_from(&claim_certificate); }) .await; assert_eq!(transfer_certificate.outgoing_message_count(), 1); chain .add_block(|block| { block.with_messages_from(&transfer_certificate); }) .await; } (application_id, accounts) } /// Queries the balance of an account owned by `account_owner` on a specific `chain`. #[cfg(all(any(test, feature = "test"), not(target_arch = "wasm32")))] pub async fn query_account( application_id: ApplicationId<FungibleTokenAbi>, chain: &ActiveChain, account_owner: AccountOwner, ) -> Option<Amount> { let query = format!( "query {{ accounts {{ entry(key: {}) {{ value }} }} }}", account_owner.to_value() ); let QueryOutcome { response, .. } = chain.graphql_query(application_id, query).await; let balance = response.pointer("/accounts/entry/value")?.as_str()?; Some( balance .parse() .expect("Account balance cannot be parsed as a number"), ) }
rust
Apache-2.0
69f159d2106f7fc70870ce70074c55850bf1303b
2026-01-04T15:33:08.660695Z
false
linera-io/linera-protocol
https://github.com/linera-io/linera-protocol/blob/69f159d2106f7fc70870ce70074c55850bf1303b/examples/fungible/src/state.rs
examples/fungible/src/state.rs
// Copyright (c) Zefchain Labs, Inc. // SPDX-License-Identifier: Apache-2.0 use fungible::{InitialState, OwnerSpender}; use linera_sdk::{ linera_base_types::{AccountOwner, Amount}, views::{linera_views, MapView, RootView, ViewStorageContext}, }; /// The application state. #[derive(RootView)] #[view(context = ViewStorageContext)] pub struct FungibleTokenState { pub accounts: MapView<AccountOwner, Amount>, pub allowances: MapView<OwnerSpender, Amount>, } #[allow(dead_code)] impl FungibleTokenState { /// Initializes the application state with some accounts with initial balances. pub(crate) async fn initialize_accounts(&mut self, state: InitialState) { for (k, v) in state.accounts { if v != Amount::ZERO { self.accounts .insert(&k, v) .expect("Error in insert statement"); } } } /// Obtains the balance for an `account`, returning None if there's no entry for the account. pub(crate) async fn balance(&self, account: &AccountOwner) -> Option<Amount> { self.accounts .get(account) .await .expect("Failure in the retrieval") } /// Obtains the balance for an `account`. pub(crate) async fn balance_or_default(&self, account: &AccountOwner) -> Amount { self.balance(account).await.unwrap_or_default() } /// Credits an `account` with the provided `amount`. pub(crate) async fn approve( &mut self, owner: AccountOwner, spender: AccountOwner, allowance: Amount, ) { if allowance == Amount::ZERO { return; } let owner_spender = OwnerSpender::new(owner, spender); let total_allowance = self .allowances .get_mut_or_default(&owner_spender) .await .expect("Failed allowance access"); total_allowance.saturating_add_assign(allowance); } pub(crate) async fn debit_for_transfer_from( &mut self, owner: AccountOwner, spender: AccountOwner, amount: Amount, ) { if amount == Amount::ZERO { return; } let mut balance = self .accounts .get(&owner) .await .expect("Failed balance access") .unwrap_or_default(); balance.try_sub_assign(amount).unwrap_or_else(|_| { panic!("Source owner {owner} does not have sufficient balance for transfer_from") }); if balance == Amount::ZERO { self.accounts .remove(&owner) .expect("Failed to remove an empty account"); } else { self.accounts .insert(&owner, balance) .expect("Failed insertion operation"); } let owner_spender = OwnerSpender::new(owner, spender); let mut allowance = self .allowances .get(&owner_spender) .await .expect("Failed allowance access") .unwrap_or_default(); allowance.try_sub_assign(amount).unwrap_or_else(|_| { panic!("Spender {spender} does not have a sufficient from owner {owner} for transfer_from; allowance={allowance} amount={amount}") }); if allowance == Amount::ZERO { self.allowances .remove(&owner_spender) .expect("Failed to remove an empty account"); } else { self.allowances .insert(&owner_spender, allowance) .expect("Failed insertion operation"); } } /// Credits an `account` with the provided `amount`. pub(crate) async fn credit(&mut self, account: AccountOwner, amount: Amount) { if amount == Amount::ZERO { return; } let mut balance = self.balance_or_default(&account).await; balance.saturating_add_assign(amount); self.accounts .insert(&account, balance) .expect("Failed insert statement"); } /// Tries to debit the requested `amount` from an `account`. pub(crate) async fn debit(&mut self, account: AccountOwner, amount: Amount) { if amount == Amount::ZERO { return; } let mut balance = self.balance_or_default(&account).await; balance.try_sub_assign(amount).unwrap_or_else(|_| { panic!("Source account {account} does not have sufficient balance for transfer") }); if balance == Amount::ZERO { self.accounts .remove(&account) .expect("Failed to remove an empty account"); } else { self.accounts .insert(&account, balance) .expect("Failed insertion operation"); } } }
rust
Apache-2.0
69f159d2106f7fc70870ce70074c55850bf1303b
2026-01-04T15:33:08.660695Z
false
linera-io/linera-protocol
https://github.com/linera-io/linera-protocol/blob/69f159d2106f7fc70870ce70074c55850bf1303b/examples/fungible/src/service.rs
examples/fungible/src/service.rs
// Copyright (c) Zefchain Labs, Inc. // SPDX-License-Identifier: Apache-2.0 #![cfg_attr(target_arch = "wasm32", no_main)] mod state; use std::sync::Arc; use async_graphql::{EmptySubscription, Object, Request, Response, Schema}; use fungible::{OwnerSpender, Parameters}; use linera_sdk::{ abis::fungible::FungibleOperation, graphql::GraphQLMutationRoot as _, linera_base_types::{AccountOwner, Amount, WithServiceAbi}, views::{MapView, View}, Service, ServiceRuntime, }; use self::state::FungibleTokenState; #[derive(Clone)] pub struct FungibleTokenService { state: Arc<FungibleTokenState>, runtime: Arc<ServiceRuntime<Self>>, } linera_sdk::service!(FungibleTokenService); impl WithServiceAbi for FungibleTokenService { type Abi = fungible::FungibleTokenAbi; } impl Service for FungibleTokenService { type Parameters = Parameters; async fn new(runtime: ServiceRuntime<Self>) -> Self { let state = FungibleTokenState::load(runtime.root_view_storage_context()) .await .expect("Failed to load state"); FungibleTokenService { state: Arc::new(state), runtime: Arc::new(runtime), } } async fn handle_query(&self, request: Request) -> Response { let schema = Schema::build( self.clone(), FungibleOperation::mutation_root(self.runtime.clone()), EmptySubscription, ) .finish(); schema.execute(request).await } } #[Object] impl FungibleTokenService { async fn accounts(&self) -> &MapView<AccountOwner, Amount> { &self.state.accounts } async fn allowances(&self) -> &MapView<OwnerSpender, Amount> { &self.state.allowances } async fn ticker_symbol(&self) -> Result<String, async_graphql::Error> { Ok(self.runtime.application_parameters().ticker_symbol) } }
rust
Apache-2.0
69f159d2106f7fc70870ce70074c55850bf1303b
2026-01-04T15:33:08.660695Z
false
linera-io/linera-protocol
https://github.com/linera-io/linera-protocol/blob/69f159d2106f7fc70870ce70074c55850bf1303b/examples/fungible/tests/cross_chain.rs
examples/fungible/tests/cross_chain.rs
// Copyright (c) Zefchain Labs, Inc. // SPDX-License-Identifier: Apache-2.0 //! Integration tests for the Fungible Token application. #![cfg(not(target_arch = "wasm32"))] use fungible::{FungibleTokenAbi, InitialState, InitialStateBuilder, Parameters}; use linera_sdk::{ abis::fungible::FungibleOperation, linera_base_types::{Account, AccountOwner, Amount}, test::{MessageAction, TestValidator}, }; /// Test transferring tokens across microchains. /// /// Creates the application on a `sender_chain`, initializing it with a single account with some /// tokens for that chain's owner. Transfers some of those tokens to a new `receiver_chain`, and /// checks that the balances on each microchain are correct. #[tokio::test] async fn test_cross_chain_transfer() { let initial_amount = Amount::from_tokens(20); let transfer_amount = Amount::from_tokens(15); let (validator, module_id) = TestValidator::with_current_module::<fungible::FungibleTokenAbi, Parameters, InitialState>( ) .await; let mut sender_chain = validator.new_chain().await; let sender_account = AccountOwner::from(sender_chain.public_key()); let initial_state = InitialStateBuilder::default().with_account(sender_account, initial_amount); let params = Parameters::new("FUN"); let application_id = sender_chain .create_application(module_id, params, initial_state.build(), vec![]) .await; let receiver_chain = validator.new_chain().await; let receiver_account = AccountOwner::from(receiver_chain.public_key()); sender_chain .add_block(|block| { block.with_operation( application_id, FungibleOperation::Transfer { owner: sender_account, amount: transfer_amount, target_account: Account { chain_id: receiver_chain.id(), owner: receiver_account, }, }, ); }) .await; assert_eq!( fungible::query_account(application_id, &sender_chain, sender_account).await, Some(initial_amount.saturating_sub(transfer_amount)), ); receiver_chain.handle_received_messages().await; assert_eq!( fungible::query_account(application_id, &receiver_chain, receiver_account).await, Some(transfer_amount), ); } /// Test bouncing some tokens back to the sender. /// /// Creates the application on a `sender_chain`, initializing it with a single account with some /// tokens for that chain's owner. Attempts to transfer some tokens to a new `receiver_chain`, /// but makes the `receiver_chain` reject the transfer message, causing the tokens to be /// returned back to the sender. #[tokio::test] async fn test_bouncing_tokens() { let initial_amount = Amount::from_tokens(19); let transfer_amount = Amount::from_tokens(7); let (validator, module_id) = TestValidator::with_current_module::<FungibleTokenAbi, Parameters, InitialState>().await; let mut sender_chain = validator.new_chain().await; let sender_account = AccountOwner::from(sender_chain.public_key()); let initial_state = InitialStateBuilder::default().with_account(sender_account, initial_amount); let params = Parameters::new("RET"); let application_id = sender_chain .create_application(module_id, params, initial_state.build(), vec![]) .await; let receiver_chain = validator.new_chain().await; let receiver_account = AccountOwner::from(receiver_chain.public_key()); let certificate = sender_chain .add_block(|block| { block.with_operation( application_id, FungibleOperation::Transfer { owner: sender_account, amount: transfer_amount, target_account: Account { chain_id: receiver_chain.id(), owner: receiver_account, }, }, ); }) .await; assert_eq!( fungible::query_account(application_id, &sender_chain, sender_account).await, Some(initial_amount.saturating_sub(transfer_amount)), ); assert_eq!(certificate.outgoing_message_count(), 1); receiver_chain .add_block(move |block| { block.with_messages_from_by_action(&certificate, MessageAction::Reject); }) .await; assert_eq!( fungible::query_account(application_id, &receiver_chain, receiver_account).await, None, ); sender_chain.handle_received_messages().await; assert_eq!( fungible::query_account(application_id, &sender_chain, sender_account).await, Some(initial_amount), ); }
rust
Apache-2.0
69f159d2106f7fc70870ce70074c55850bf1303b
2026-01-04T15:33:08.660695Z
false
linera-io/linera-protocol
https://github.com/linera-io/linera-protocol/blob/69f159d2106f7fc70870ce70074c55850bf1303b/examples/amm/src/contract.rs
examples/amm/src/contract.rs
// Copyright (c) Zefchain Labs, Inc. // SPDX-License-Identifier: Apache-2.0 #![cfg_attr(target_arch = "wasm32", no_main)] mod state; use amm::{AmmAbi, Message, Operation, Parameters}; use linera_sdk::{ abis::fungible::{FungibleOperation, FungibleResponse, FungibleTokenAbi}, linera_base_types::{Account, AccountOwner, Amount, ApplicationId, ChainId, WithContractAbi}, views::{RootView, View}, Contract, ContractRuntime, }; use num_bigint::BigUint; use num_traits::{cast::FromPrimitive, ToPrimitive}; use self::state::AmmState; pub struct AmmContract { state: AmmState, runtime: ContractRuntime<Self>, } linera_sdk::contract!(AmmContract); impl WithContractAbi for AmmContract { type Abi = AmmAbi; } impl Contract for AmmContract { type Message = Message; type InstantiationArgument = (); type Parameters = Parameters; type EventValue = (); async fn load(runtime: ContractRuntime<Self>) -> Self { let state = AmmState::load(runtime.root_view_storage_context()) .await .expect("Failed to load state"); AmmContract { state, runtime } } async fn instantiate(&mut self, _argument: ()) { // Validate that the application parameters were configured correctly. self.runtime.application_parameters(); } async fn execute_operation(&mut self, operation: Self::Operation) -> Self::Response { if self.runtime.chain_id() == self.runtime.application_creator_chain_id() { self.execute_order_local(operation).await; } else { self.execute_order_remote(operation).await; } } async fn execute_message(&mut self, message: Self::Message) { assert_eq!( self.runtime.chain_id(), self.runtime.application_creator_chain_id(), "Action can only be executed on the chain that created the AMM" ); match message { Message::Swap { owner, input_token_idx, input_amount, } => { self.runtime .check_account_permission(owner) .expect("Permission for Swap message"); // It's assumed that the tokens have already been transferred here at this point assert!( input_amount > Amount::ZERO, "You can't swap with zero tokens" ); assert!(input_token_idx < 2, "Invalid token index"); let output_token_idx = 1 - input_token_idx; let input_pool_balance = self.get_pool_balance(input_token_idx); let output_pool_balance = self.get_pool_balance(output_token_idx); let output_amount = self.calculate_output_amount( input_amount, input_pool_balance, output_pool_balance, ); let amm_account = self.get_amm_account(); self.transfer(owner, input_amount, amm_account, input_token_idx); let amm_app_owner = self.get_amm_app_owner(); let message_origin_account = self.get_message_origin_account(owner); self.transfer( amm_app_owner, output_amount, message_origin_account, output_token_idx, ); } Message::AddLiquidity { owner, max_token0_amount, max_token1_amount, } => { self.runtime .check_account_permission(owner) .expect("Permission for AddLiquidity message"); assert!( max_token0_amount > Amount::ZERO && max_token1_amount > Amount::ZERO, "You can't add liquidity with zero tokens" ); let balance0 = self.get_pool_balance(0); let balance1 = self.get_pool_balance(1); let balance0_bigint = BigUint::from_u128(u128::from(balance0)) .expect("Couldn't generate balance0 in bigint"); let balance1_bigint = BigUint::from_u128(u128::from(balance1)) .expect("Couldn't generate balance1 in bigint"); let token0_amount; let token1_amount; if balance0 > Amount::ZERO && balance1 > Amount::ZERO { let max_token0_amount_bigint = BigUint::from_u128(u128::from(max_token0_amount)) .expect("Couldn't generate max_token0_amount in bigint"); let max_token1_amount_bigint = BigUint::from_u128(u128::from(max_token1_amount)) .expect("Couldn't generate max_token1_amount in bigint"); // This is the formula to maintain the ratio: // balance0 / balance1 = (balance0 + max_token0_amount) / (balance1 + token1_amount) // balance0 * (balance1 + token1_amount) = balance1 * (balance0 + max_token0_amount) // balance0 * balance1 + balance0 * token1_amount = balance1 * balance0 + balance1 * max_token0_amount // balance0 * token1_amount = balance1 * max_token0_amount // token1_amount = (balance1 * max_token0_amount) / balance0 // // For token0_amount, it would be this: // token0_amount = (balance0 * max_token1_amount) / balance1 if &max_token0_amount_bigint * &balance1_bigint > &max_token1_amount_bigint * &balance0_bigint { let token0_amount_bigint = (&balance0_bigint * &max_token1_amount_bigint) / &balance1_bigint; token0_amount = Amount::from_attos( token0_amount_bigint .to_u128() .expect("Couldn't convert token0_amount_bigint to u128"), ); token1_amount = Amount::from_attos( max_token1_amount_bigint .to_u128() .expect("Couldn't convert max_token1_amount_bigint to u128"), ); } else { let token1_amount_bigint = (&balance1_bigint * &max_token0_amount_bigint) / &balance0_bigint; token0_amount = Amount::from_attos( max_token0_amount_bigint .to_u128() .expect("Couldn't convert max_token0_amount_bigint to u128"), ); token1_amount = Amount::from_attos( token1_amount_bigint .to_u128() .expect("Couldn't convert token1_amount_bigint to u128"), ); } } else { // This means we're on the first liquidity addition token0_amount = max_token0_amount; token1_amount = max_token1_amount; } let amm_account = self.get_amm_account(); let message_origin_account = self.get_message_origin_account(owner); // See if we'll need to send refunds if token0_amount < max_token0_amount { self.transfer( owner, max_token0_amount.saturating_sub(token0_amount), message_origin_account, 0, ); } // Transfer tokens to AMM owner self.transfer(owner, token0_amount, amm_account, 0); // See if we'll need to send refunds if token1_amount < max_token1_amount { self.transfer( owner, max_token1_amount.saturating_sub(token1_amount), message_origin_account, 1, ); } // Transfer tokens to AMM owner self.transfer(owner, token1_amount, amm_account, 1); let shares_to_mint = self.get_shares(token0_amount, token1_amount, &balance0_bigint); let mut current_shares = self .current_shares_or_default(&message_origin_account) .await; current_shares.saturating_add_assign(shares_to_mint); self.state .shares .insert(&message_origin_account, current_shares) .expect("Failed insert statement"); let total_shares_supply = self.state.total_shares_supply.get_mut(); *total_shares_supply = total_shares_supply.saturating_add(shares_to_mint); } Message::RemoveLiquidity { owner, token_to_remove_idx, mut token_to_remove_amount, } => { self.runtime .check_account_permission(owner) .expect("Permission for RemoveLiquidity message"); assert!(token_to_remove_idx < 2, "Invalid token index"); let balance0 = self.get_pool_balance(0); let balance1 = self.get_pool_balance(1); if token_to_remove_idx == 0 && token_to_remove_amount > balance0 { token_to_remove_amount = balance0; } else if token_to_remove_idx == 1 && token_to_remove_amount > balance1 { token_to_remove_amount = balance1; } let token_to_remove_amount_bigint = BigUint::from_u128(u128::from(token_to_remove_amount)) .expect("Couldn't generate token_to_remove_amount in bigint"); let balance0_bigint = BigUint::from_u128(u128::from(balance0)) .expect("Couldn't generate balance0 in bigint"); let balance1_bigint = BigUint::from_u128(u128::from(balance1)) .expect("Couldn't generate balance1 in bigint"); let other_amount = if token_to_remove_idx == 0 { Amount::from_attos( ((token_to_remove_amount_bigint * balance1_bigint.clone()) / balance0_bigint.clone()) .to_u128() .expect("Couldn't convert other_amount to u128"), ) } else { Amount::from_attos( ((token_to_remove_amount_bigint * balance0_bigint.clone()) / balance1_bigint.clone()) .to_u128() .expect("Couldn't convert other_amount to u128"), ) }; let shares_to_return = if token_to_remove_idx == 0 { self.get_shares(token_to_remove_amount, other_amount, &balance0_bigint) } else { self.get_shares(other_amount, token_to_remove_amount, &balance0_bigint) }; let message_origin_account = self.get_message_origin_account(owner); let current_shares = self .current_shares_or_default(&message_origin_account) .await; assert!( shares_to_return <= current_shares, "Can't remove more liquidity than you added" ); self.return_shares( message_origin_account, current_shares, shares_to_return, token_to_remove_idx, token_to_remove_amount, other_amount, ) } Message::RemoveAllAddedLiquidity { owner } => { self.runtime .check_account_permission(owner) .expect("Permission for RemoveAllAddedLiquidity message"); let message_origin_account = self.get_message_origin_account(owner); let current_shares = self .current_shares_or_default(&message_origin_account) .await; let (amount_token0, amount_token1) = self.get_amounts_from_shares(current_shares); self.return_shares( message_origin_account, current_shares, current_shares, 0, amount_token0, amount_token1, ); } } } async fn store(mut self) { self.state.save().await.expect("Failed to save state"); } } impl AmmContract { /// Obtains the current shares for an `account`. async fn current_shares_or_default(&self, account: &Account) -> Amount { self.state .shares .get(account) .await .expect("Failure in the retrieval") .unwrap_or_default() } fn return_shares( &mut self, account: Account, mut current_shares: Amount, shares_to_return: Amount, token_to_remove_idx: u32, token_to_remove_amount: Amount, other_token_to_remove_amount: Amount, ) { let amm_app_owner = self.get_amm_app_owner(); self.transfer( amm_app_owner, token_to_remove_amount, account, token_to_remove_idx, ); self.transfer( amm_app_owner, other_token_to_remove_amount, account, 1 - token_to_remove_idx, ); current_shares = current_shares.saturating_sub(shares_to_return); if current_shares == Amount::ZERO { self.state .shares .remove(&account) .expect("Failed remove statement"); } else { self.state .shares .insert(&account, current_shares) .expect("Failed insert statement"); } let total_shares_supply = self.state.total_shares_supply.get_mut(); *total_shares_supply = total_shares_supply.saturating_sub(shares_to_return); } fn get_shares( &self, token0_amount: Amount, token1_amount: Amount, balance0_bigint: &BigUint, ) -> Amount { let token0_amount_bigint = BigUint::from_u128(u128::from(token0_amount)) .expect("Converting token0_amount to BigUint should not fail!"); let token1_amount_bigint = BigUint::from_u128(u128::from(token1_amount)) .expect("Converting token1_amount to BigUint should not fail!"); if *self.state.total_shares_supply.get() == Amount::ZERO { let tokens_mul_bigint = token0_amount_bigint * token1_amount_bigint; Amount::from_attos( BigUint::sqrt(&tokens_mul_bigint) .to_u128() .expect("Couldn't convert BigUint shares to u128"), ) } else { let total_shares_supply_bigint = BigUint::from_u128(u128::from(*self.state.total_shares_supply.get())) .expect("Converting total_shares_supply to BigUint should not fail!"); Amount::from_attos( ((token0_amount_bigint * total_shares_supply_bigint.clone()) / balance0_bigint) .to_u128() .expect("Couldn't convert BigUint shares to u128"), ) } } fn get_amounts_from_shares(&mut self, current_shares: Amount) -> (Amount, Amount) { let total_shares_supply = *self.state.total_shares_supply.get(); let balance0 = self.get_pool_balance(0); let balance1 = self.get_pool_balance(1); let total_shares_supply_bigint = BigUint::from_u128(u128::from(total_shares_supply)) .expect("Couldn't generate total_shares_supply in bigint"); let current_shares_bigint = BigUint::from_u128(u128::from(current_shares)) .expect("Couldn't generate current_shares in bigint"); let balance0_bigint = BigUint::from_u128(u128::from(balance0)).expect("Couldn't generate balance0 in bigint"); let balance1_bigint = BigUint::from_u128(u128::from(balance1)).expect("Couldn't generate balance1 in bigint"); ( Amount::from_attos( ((current_shares_bigint.clone() * balance0_bigint) / total_shares_supply_bigint.clone()) .to_u128() .expect("Couldn't convert amount_token0 to u128"), ), Amount::from_attos( ((current_shares_bigint * balance1_bigint) / total_shares_supply_bigint) .to_u128() .expect("Couldn't convert amount_token1 to u128"), ), ) } fn get_amm_app_owner(&mut self) -> AccountOwner { self.runtime.application_id().into() } fn get_amm_chain_id(&mut self) -> ChainId { self.runtime.application_creator_chain_id() } fn get_amm_account(&mut self) -> Account { Account { chain_id: self.get_amm_chain_id(), owner: self.get_amm_app_owner(), } } fn get_message_origin_account(&mut self, owner: AccountOwner) -> Account { Account { chain_id: self .runtime .message_origin_chain_id() .expect("Getting message origin chain ID should not fail"), owner, } } fn get_account_on_amm_chain(&mut self, owner: AccountOwner) -> Account { Account { chain_id: self.get_amm_chain_id(), owner, } } async fn execute_order_local(&mut self, operation: Operation) { match operation { Operation::Swap { owner: _, input_token_idx: _, input_amount: _, } => panic!("Can't swap locally"), Operation::AddLiquidity { owner: _, max_token0_amount: _, max_token1_amount: _, } => panic!("Can't add liquidity locally"), Operation::RemoveLiquidity { owner: _, token_to_remove_idx: _, token_to_remove_amount: _, } => panic!("Can't remove liquidity locally"), Operation::RemoveAllAddedLiquidity { owner: _ } => { panic!("Can't remove liquidity locally") } Operation::CloseChain => { let accounts = self .state .shares .indices() .await .expect("Failed to load list of share owners"); for account in accounts { let current_shares = self.current_shares_or_default(&account).await; let (amount_token0, amount_token1) = self.get_amounts_from_shares(current_shares); self.return_shares( account, current_shares, current_shares, 0, amount_token0, amount_token1, ); } assert_eq!( *self.state.total_shares_supply.get(), Amount::ZERO, "Untracked liquidity was found" ); self.runtime .close_chain() .expect("Application is not authorized to close the chain"); } } } async fn execute_order_remote(&mut self, operation: Operation) { match operation { Operation::Swap { owner, input_token_idx, input_amount, } => { self.runtime .check_account_permission(owner) .expect("Permission for Swap operation"); let account_on_amm_chain = self.get_account_on_amm_chain(owner); self.transfer(owner, input_amount, account_on_amm_chain, input_token_idx); let message = Message::Swap { owner, input_token_idx, input_amount, }; self.runtime .prepare_message(message) .with_authentication() .send_to(self.get_amm_chain_id()); } Operation::AddLiquidity { owner, max_token0_amount, max_token1_amount, } => { self.runtime .check_account_permission(owner) .expect("Permission for AddLiquidity operation"); let account_on_amm_chain = self.get_account_on_amm_chain(owner); self.transfer(owner, max_token0_amount, account_on_amm_chain, 0); self.transfer(owner, max_token1_amount, account_on_amm_chain, 1); let message = Message::AddLiquidity { owner, max_token0_amount, max_token1_amount, }; self.runtime .prepare_message(message) .with_authentication() .send_to(self.get_amm_chain_id()); } // When removing liquidity, you'll specify one of the tokens you want to // remove and the amount, and we'll calculate the amount for the other token that // we'll remove based on the current ratio, and remove them. Operation::RemoveLiquidity { owner, token_to_remove_idx, token_to_remove_amount, } => { self.runtime .check_account_permission(owner) .expect("Permission for RemoveLiquidity operation"); let message = Message::RemoveLiquidity { owner, token_to_remove_idx, token_to_remove_amount, }; self.runtime .prepare_message(message) .with_authentication() .send_to(self.get_amm_chain_id()); } Operation::RemoveAllAddedLiquidity { owner } => { self.runtime .check_account_permission(owner) .expect("Permission for RemoveAllAddedLiquidity operation"); let message = Message::RemoveAllAddedLiquidity { owner }; self.runtime .prepare_message(message) .with_authentication() .send_to(self.get_amm_chain_id()); } Operation::CloseChain => panic!("Can't close the chain remotely"), } } fn calculate_output_amount( &mut self, input_amount: Amount, input_pool_balance: Amount, output_pool_balance: Amount, ) -> Amount { assert!( input_pool_balance > Amount::ZERO && output_pool_balance > Amount::ZERO, "Invalid pool balance" ); let input_amount_bigint = BigUint::from_u128(u128::from(input_amount)) .expect("Couldn't generate input_amount in bigint"); let output_pool_balance_bigint = BigUint::from_u128(u128::from(output_pool_balance)) .expect("Couldn't generate output_pool_balance in bigint"); let input_pool_balance_bigint = BigUint::from_u128(u128::from(input_pool_balance)) .expect("Couldn't generate input_pool_balance in bigint"); // Logic for this is the following: // This is a Constant Product Automated Market Maker, or CPAMM, so we want // the product to remain constant. // That means that this is the equation we need to solve to find output_amount: // (input_pool_balance + input_amount) * (output_pool_balance - output_amount) = input_pool_balance * output_pool_balance // output_pool_balance - output_amount = (input_pool_balance * output_pool_balance) / (input_pool_balance + input_amount) // output_amount = output_pool_balance - (input_pool_balance * output_pool_balance) / (input_pool_balance + input_amount) // output_amount = (output_pool_balance * (input_pool_balance + input_amount) - (input_pool_balance * output_pool_balance)) / (input_pool_balance + input_amount) // output_amount = (input_pool_balance * output_pool_balance + input_amount * output_pool_balance - input_pool_balance * output_pool_balance) / (input_pool_balance + input_amount) // output_amount = (input_amount * output_pool_balance) / (input_pool_balance + input_amount) // Numerator will be a number with 36 decimal points here let numerator_bigint = &input_amount_bigint * output_pool_balance_bigint; // Denominator will have 18 decimal points let denominator_bigint = input_pool_balance_bigint + input_amount_bigint; // Dividing 36 decimal points with 18 decimal points = 18 decimal points let output_amount_bigint = numerator_bigint / denominator_bigint; Amount::from_attos( output_amount_bigint .to_u128() .expect("Couldn't convert output_amount_bigint to u128"), ) } fn get_pool_balance(&mut self, token_idx: u32) -> Amount { let pool_owner = self.runtime.application_id().into(); self.balance(&pool_owner, token_idx) } fn fungible_id(&mut self, token_idx: u32) -> ApplicationId<FungibleTokenAbi> { self.runtime.application_parameters().tokens[token_idx as usize] } fn transfer( &mut self, source_owner: AccountOwner, amount: Amount, target_account: Account, token_idx: u32, ) { let token = self.fungible_id(token_idx); let operation = FungibleOperation::Transfer { owner: source_owner, amount, target_account, }; self.runtime.call_application(true, token, &operation); } fn balance(&mut self, owner: &AccountOwner, token_idx: u32) -> Amount { let balance = FungibleOperation::Balance { owner: *owner }; let token = self.fungible_id(token_idx); match self.runtime.call_application(true, token, &balance) { FungibleResponse::Balance(balance) => balance, response => panic!("Unexpected response from fungible token application: {response:?}"), } } }
rust
Apache-2.0
69f159d2106f7fc70870ce70074c55850bf1303b
2026-01-04T15:33:08.660695Z
false
linera-io/linera-protocol
https://github.com/linera-io/linera-protocol/blob/69f159d2106f7fc70870ce70074c55850bf1303b/examples/amm/src/lib.rs
examples/amm/src/lib.rs
// Copyright (c) Zefchain Labs, Inc. // SPDX-License-Identifier: Apache-2.0 /*! The ABI for the Automated Market Maker (AMM) Example Application */ use async_graphql::{scalar, Request, Response}; use linera_sdk::{ abis::fungible::FungibleTokenAbi, graphql::GraphQLMutationRoot, linera_base_types::{AccountOwner, Amount, ApplicationId, ContractAbi, ServiceAbi}, }; use serde::{Deserialize, Serialize}; pub struct AmmAbi; impl ContractAbi for AmmAbi { type Operation = Operation; type Response = (); } impl ServiceAbi for AmmAbi { type Query = Request; type QueryResponse = Response; } /// Operations that can be sent to the application. #[derive(Debug, Serialize, Deserialize, GraphQLMutationRoot)] pub enum Operation { // TODO(#969): Need to also implement Swap Bids here /// Swap operation /// Given an input token idx (can be 0 or 1), and an input amount, /// Swap that token amount for an amount of the other token, /// calculated based on the current AMM ratio /// `owner` here is the user executing the Swap Swap { owner: AccountOwner, input_token_idx: u32, input_amount: Amount, }, /// Add liquidity operation /// Given a maximum token0 and token1 amount that you're willing to add, /// add liquidity to the AMM such that you'll be adding AT MOST /// `max_token0_amount` of token0, and `max_token1_amount` of token1, /// which will be calculated based on the current AMM ratio /// `owner` here is the user adding liquidity, which currently can only /// be a chain owner AddLiquidity { owner: AccountOwner, max_token0_amount: Amount, max_token1_amount: Amount, }, /// Remove liquidity operation /// Given a token idx of the token you'd like to remove (can be 0 or 1), /// and an amount of that token that you'd like to remove, we'll calculate /// how much of the other token will also be removed, which will be calculated /// based on the current AMM ratio. Then remove the amounts from both tokens /// as a removal of liquidity /// `owner` here is the user removing liquidity, which currently can only /// be a chain owner RemoveLiquidity { owner: AccountOwner, token_to_remove_idx: u32, token_to_remove_amount: Amount, }, /// Remove all added liquidity operation /// Remove all the liquidity added by the given user, that is remaining in the AMM. /// `owner` here is the user removing liquidity, which currently can only /// be a chain owner RemoveAllAddedLiquidity { owner: AccountOwner }, /// Close this chain, and remove all added liquidity /// Requires that this application is authorized to close the chain. CloseChain, } scalar!(Operation); #[derive(Debug, Deserialize, Serialize)] pub enum Message { Swap { owner: AccountOwner, input_token_idx: u32, input_amount: Amount, }, AddLiquidity { owner: AccountOwner, max_token0_amount: Amount, max_token1_amount: Amount, }, RemoveLiquidity { owner: AccountOwner, token_to_remove_idx: u32, token_to_remove_amount: Amount, }, RemoveAllAddedLiquidity { owner: AccountOwner, }, } /// The parameters used when an AMM application is instantiated. #[derive(Clone, Copy, Debug, Deserialize, Serialize)] pub struct Parameters { /// The token0 and token1 used for the AMM. pub tokens: [ApplicationId<FungibleTokenAbi>; 2], } scalar!(Parameters);
rust
Apache-2.0
69f159d2106f7fc70870ce70074c55850bf1303b
2026-01-04T15:33:08.660695Z
false
linera-io/linera-protocol
https://github.com/linera-io/linera-protocol/blob/69f159d2106f7fc70870ce70074c55850bf1303b/examples/amm/src/state.rs
examples/amm/src/state.rs
// Copyright (c) Zefchain Labs, Inc. // SPDX-License-Identifier: Apache-2.0 use linera_sdk::{ linera_base_types::{Account, Amount}, views::{linera_views, MapView, RegisterView, RootView, ViewStorageContext}, }; #[derive(RootView, async_graphql::SimpleObject)] #[view(context = ViewStorageContext)] pub struct AmmState { pub shares: MapView<Account, Amount>, pub total_shares_supply: RegisterView<Amount>, }
rust
Apache-2.0
69f159d2106f7fc70870ce70074c55850bf1303b
2026-01-04T15:33:08.660695Z
false
linera-io/linera-protocol
https://github.com/linera-io/linera-protocol/blob/69f159d2106f7fc70870ce70074c55850bf1303b/examples/amm/src/service.rs
examples/amm/src/service.rs
// Copyright (c) Zefchain Labs, Inc. // SPDX-License-Identifier: Apache-2.0 #![cfg_attr(target_arch = "wasm32", no_main)] mod state; use std::sync::Arc; use amm::{Operation, Parameters}; use async_graphql::{EmptySubscription, Request, Response, Schema}; use linera_sdk::{ graphql::GraphQLMutationRoot as _, linera_base_types::WithServiceAbi, views::View, Service, ServiceRuntime, }; use self::state::AmmState; pub struct AmmService { state: Arc<AmmState>, runtime: Arc<ServiceRuntime<Self>>, } linera_sdk::service!(AmmService); impl WithServiceAbi for AmmService { type Abi = amm::AmmAbi; } impl Service for AmmService { type Parameters = Parameters; async fn new(runtime: ServiceRuntime<Self>) -> Self { let state = AmmState::load(runtime.root_view_storage_context()) .await .expect("Failed to load state"); AmmService { state: Arc::new(state), runtime: Arc::new(runtime), } } async fn handle_query(&self, request: Request) -> Response { let schema = Schema::build( self.state.clone(), Operation::mutation_root(self.runtime.clone()), EmptySubscription, ) .finish(); schema.execute(request).await } }
rust
Apache-2.0
69f159d2106f7fc70870ce70074c55850bf1303b
2026-01-04T15:33:08.660695Z
false
linera-io/linera-protocol
https://github.com/linera-io/linera-protocol/blob/69f159d2106f7fc70870ce70074c55850bf1303b/examples/rfq/src/contract.rs
examples/rfq/src/contract.rs
// Copyright (c) Zefchain Labs, Inc. // SPDX-License-Identifier: Apache-2.0 #![cfg_attr(target_arch = "wasm32", no_main)] mod state; use fungible::{FungibleOperation, FungibleTokenAbi}; use linera_sdk::{ linera_base_types::{ Account, AccountOwner, Amount, ApplicationPermissions, ChainId, ChainOwnership, TimeoutConfig, WithContractAbi, }, views::{RootView, View}, Contract, ContractRuntime, }; use rfq::{Message, Operation, RequestId, RfqAbi, TokenPair, Tokens}; use self::state::{QuoteProvided, RfqState}; pub struct RfqContract { state: RfqState, runtime: ContractRuntime<Self>, } linera_sdk::contract!(RfqContract); impl WithContractAbi for RfqContract { type Abi = RfqAbi; } impl Contract for RfqContract { type Message = Message; type InstantiationArgument = (); type Parameters = (); type EventValue = (); async fn load(runtime: ContractRuntime<Self>) -> Self { let state = RfqState::load(runtime.root_view_storage_context()) .await .expect("Failed to load state"); RfqContract { state, runtime } } async fn instantiate(&mut self, _argument: ()) { // Validate that the application parameters were configured correctly. self.runtime.application_parameters(); } async fn execute_operation(&mut self, operation: Self::Operation) -> Self::Response { if self.state.is_temp_chain() { // No operations should be executed directly on a temporary chain return; } match operation { Operation::RequestQuote { target, token_pair, amount, } => { let seq_number = self .state .create_new_request(target, token_pair.clone(), amount); let message = Message::RequestQuote { seq_number, token_pair, amount, }; self.runtime .prepare_message(message) .with_authentication() .send_to(target); } Operation::ProvideQuote { request_id, quote, quoter_owner, } => { let request_data = self .state .request_data(&request_id) .await .expect("Request not found!"); if request_id.is_our_request() { panic!("Tried to provide a quote for our own request!"); } request_data.update_state_with_quote(quote, quoter_owner); let message = Message::ProvideQuote { seq_number: request_id.seq_number(), quote, quoter_owner, }; self.runtime .prepare_message(message) .with_authentication() .send_to(request_id.chain_id()) } Operation::AcceptQuote { request_id, owner, fee_budget, } => { let request_data = self .state .request_data(&request_id) .await .expect("Request not found!"); if !request_id.is_our_request() { panic!("Tried to accept a quote we have provided"); } let quote_provided = request_data.quote_provided(); let token_pair = request_data.token_pair(); let temp_chain_id = self .start_exchange( request_id.clone(), quote_provided, token_pair, fee_budget, owner, ) .await; self.state .request_data(&request_id) .await .expect("Request not found!") .start_exchange(temp_chain_id); } Operation::FinalizeDeal { request_id } => { let request_data = self .state .request_data(&request_id) .await .expect("Request not found!"); let awaiting_tokens = request_data.awaiting_tokens(); let owner = awaiting_tokens.quoter_account; // the message should have been sent from the temporary chain let temp_chain_id = awaiting_tokens.temp_chain_id; // transfer tokens to the new chain let token_pair = awaiting_tokens.token_pair; let transfer = FungibleOperation::Transfer { owner, amount: awaiting_tokens.amount_offered, target_account: Account { chain_id: temp_chain_id, owner: self.runtime.application_id().into(), }, }; let token = token_pair.token_asked; self.runtime.call_application( true, token.with_abi::<FungibleTokenAbi>(), &transfer, ); let message = Message::TokensSent { tokens: Box::new(Tokens { token_id: token, owner: Account { chain_id: self.runtime.chain_id(), owner, }, amount: awaiting_tokens.amount_offered, }), }; self.runtime .prepare_message(message) .with_authentication() .send_to(temp_chain_id); request_data.start_exchange(temp_chain_id); } Operation::CancelRequest { request_id } => { if let Some(temp_chain_id) = self.state.cancel_request(&request_id).await { let message = Message::CloseChain; self.runtime .prepare_message(message) .with_authentication() .send_to(temp_chain_id); } else { let message = Message::CancelRequest { seq_number: request_id.seq_number(), recipient_requested: !request_id.is_our_request(), }; self.runtime .prepare_message(message) .with_authentication() .send_to(request_id.chain_id()); } } } } async fn execute_message(&mut self, message: Self::Message) { let origin_chain_id = self .runtime .message_origin_chain_id() .expect("Getting message origin chain ID should not fail"); let request_id = message.request_id(origin_chain_id); match message { Message::RequestQuote { token_pair, amount, .. } => { self.state.register_request(request_id, token_pair, amount); } Message::ProvideQuote { quote, quoter_owner, .. } => { self.state .request_data(&request_id) .await .expect("Request not found!") .update_state_with_quote(quote, quoter_owner); } Message::QuoteAccepted { request_id } => { self.state .request_data(&request_id) .await .expect("Request not found!") .accept_quote(origin_chain_id); } Message::CancelRequest { .. } => { if let Some(temp_chain_id) = self.state.cancel_request(&request_id).await { // the other side wasn't aware of the chain yet, or they would have // sent `RequestClosed` - we have to close it ourselves let message = Message::CloseChain; self.runtime .prepare_message(message) .with_authentication() .send_to(temp_chain_id); } } Message::ChainClosed { request_id } => { self.state.close_request(&request_id).await; } // the message below should only be executed on the temporary chains Message::StartExchange { request_id, initiator, token_pair, tokens, } => { // save the info in the app state self.state.init_temp_chain_state( request_id.clone(), initiator, *token_pair, *tokens, ); // inform the other side that the temporary chain is ready let message = Message::QuoteAccepted { request_id: RequestId::new(initiator, request_id.seq_number(), false), }; self.runtime .prepare_message(message) .with_authentication() .send_to(request_id.chain_id()); } Message::TokensSent { tokens } => { match self.state.take_temp_chain_held_tokens() { None => { // This should never really happen, but if it does, return the // sent tokens let owner = self.runtime.application_id().into(); self.runtime.call_application( true, tokens.token_id.with_abi::<fungible::FungibleTokenAbi>(), &FungibleOperation::Transfer { owner, amount: tokens.amount, target_account: tokens.owner, }, ); } Some(held_tokens) => { // we have tokens from both parties now: return them to the // correct parties let owner = self.runtime.application_id().into(); self.runtime.call_application( true, tokens.token_id.with_abi::<fungible::FungibleTokenAbi>(), &FungibleOperation::Transfer { owner, amount: tokens.amount, target_account: held_tokens.owner, }, ); self.runtime.call_application( true, held_tokens .token_id .with_abi::<fungible::FungibleTokenAbi>(), &FungibleOperation::Transfer { owner, amount: held_tokens.amount, target_account: tokens.owner, }, ); } } // exchange is finished, we can close the chain self.close_chain(); } Message::CloseChain => { self.close_chain(); } } } async fn store(mut self) { self.state.save().await.expect("Failed to save state"); } } impl RfqContract { async fn start_exchange( &mut self, request_id: RequestId, quote_provided: QuoteProvided, token_pair: TokenPair, fee_budget: Amount, owner: AccountOwner, ) -> ChainId { let ownership = ChainOwnership::multiple( [(owner, 100), (quote_provided.get_quoter_owner(), 100)], 100, TimeoutConfig::default(), ); let app_id = self.runtime.application_id(); let permissions = ApplicationPermissions::new_single(app_id.forget_abi()); let temp_chain_id = self.runtime.open_chain(ownership, permissions, fee_budget); // transfer tokens to the new chain let transfer = FungibleOperation::Transfer { owner, amount: quote_provided.get_amount(), target_account: Account { chain_id: temp_chain_id, owner: self.runtime.application_id().into(), }, }; let token = token_pair.token_offered; self.runtime .call_application(true, token.with_abi::<FungibleTokenAbi>(), &transfer); // signal to the temporary chain that it should start the exchange! let initiator = self.runtime.chain_id(); let message = Message::StartExchange { initiator, request_id, token_pair: Box::new(token_pair), tokens: Box::new(Tokens { token_id: token, owner: Account { chain_id: self.runtime.chain_id(), owner, }, amount: quote_provided.get_amount(), }), }; self.runtime .prepare_message(message) .with_authentication() .send_to(temp_chain_id); temp_chain_id } fn close_chain(&mut self) { // we're executing on the temporary chain // if we hold some tokens, we return them before closing if let Some(tokens) = self.state.temp_chain_held_tokens() { let owner = self.runtime.application_id().into(); self.runtime.call_application( true, tokens.token_id.with_abi::<fungible::FungibleTokenAbi>(), &FungibleOperation::Transfer { owner, amount: tokens.amount, target_account: tokens.owner, }, ); } self.runtime .close_chain() .expect("Failed to close the temporary chain"); // let both users know that the chain is now closed let (initiator, request_id) = self.state.temp_chain_initiator_and_request_id(); let message = Message::ChainClosed { request_id: request_id.clone(), }; self.runtime .prepare_message(message) .with_authentication() .send_to(initiator); let other_chain = request_id.chain_id(); let request_id = RequestId::new(initiator, request_id.seq_number(), false); let message = Message::ChainClosed { request_id }; self.runtime .prepare_message(message) .with_authentication() .send_to(other_chain); } }
rust
Apache-2.0
69f159d2106f7fc70870ce70074c55850bf1303b
2026-01-04T15:33:08.660695Z
false
linera-io/linera-protocol
https://github.com/linera-io/linera-protocol/blob/69f159d2106f7fc70870ce70074c55850bf1303b/examples/rfq/src/lib.rs
examples/rfq/src/lib.rs
// Copyright (c) Zefchain Labs, Inc. // SPDX-License-Identifier: Apache-2.0 /*! ABI of the Requests For Quotes Example Application */ use async_graphql::{scalar, InputObject, Request, Response, SimpleObject}; use linera_sdk::{ graphql::GraphQLMutationRoot, linera_base_types::{ Account, AccountOwner, Amount, ApplicationId, ChainId, ContractAbi, ServiceAbi, }, }; use serde::{Deserialize, Serialize}; pub struct RfqAbi; impl ContractAbi for RfqAbi { type Operation = Operation; type Response = (); } impl ServiceAbi for RfqAbi { type Query = Request; type QueryResponse = Response; } #[derive(Debug, Clone, Serialize, Deserialize, SimpleObject, InputObject)] #[graphql(input_name = "TokenPairInput")] pub struct TokenPair { pub token_offered: ApplicationId, pub token_asked: ApplicationId, } #[derive(Debug, Clone, Serialize, Deserialize, SimpleObject, InputObject)] #[graphql(input_name = "RequestIdInput")] pub struct RequestId { other_chain_id: ChainId, seq_num: u64, we_requested: bool, } impl RequestId { pub fn new(other_chain_id: ChainId, seq_num: u64, we_requested: bool) -> Self { Self { other_chain_id, seq_num, we_requested, } } pub fn chain_id(&self) -> ChainId { self.other_chain_id } pub fn seq_number(&self) -> u64 { self.seq_num } pub fn is_our_request(&self) -> bool { self.we_requested } pub fn with_we_requested(self, we_requested: bool) -> Self { Self { we_requested, ..self } } } #[derive(Debug, Clone, Serialize, Deserialize, SimpleObject, InputObject)] #[graphql(input_name = "TokensInput")] pub struct Tokens { pub token_id: ApplicationId, pub owner: Account, pub amount: Amount, } /// Operations that can be sent to the application. #[derive(Debug, Serialize, Deserialize, GraphQLMutationRoot)] pub enum Operation { RequestQuote { target: ChainId, token_pair: TokenPair, amount: Amount, }, ProvideQuote { request_id: RequestId, quote: Amount, quoter_owner: AccountOwner, }, AcceptQuote { request_id: RequestId, owner: AccountOwner, fee_budget: Amount, }, FinalizeDeal { request_id: RequestId, }, CancelRequest { request_id: RequestId, }, } scalar!(Operation); #[derive(Debug, Deserialize, Serialize)] pub enum Message { RequestQuote { seq_number: u64, token_pair: TokenPair, amount: Amount, }, ProvideQuote { seq_number: u64, quote: Amount, quoter_owner: AccountOwner, }, QuoteAccepted { request_id: RequestId, }, CancelRequest { seq_number: u64, recipient_requested: bool, }, StartExchange { initiator: ChainId, request_id: RequestId, token_pair: Box<TokenPair>, tokens: Box<Tokens>, }, TokensSent { tokens: Box<Tokens>, }, CloseChain, ChainClosed { request_id: RequestId, }, } impl Message { pub fn request_id(&self, other_chain_id: ChainId) -> RequestId { match self { Message::RequestQuote { seq_number, .. } => { RequestId::new(other_chain_id, *seq_number, false) } Message::ProvideQuote { seq_number, .. } => { RequestId::new(other_chain_id, *seq_number, true) } Message::QuoteAccepted { request_id } | Message::StartExchange { request_id, .. } | Message::ChainClosed { request_id } => request_id.clone(), Message::CancelRequest { seq_number, recipient_requested, } => RequestId::new(other_chain_id, *seq_number, *recipient_requested), Message::TokensSent { .. } | Message::CloseChain => { // unused RequestId::new(other_chain_id, 0, false) } } } }
rust
Apache-2.0
69f159d2106f7fc70870ce70074c55850bf1303b
2026-01-04T15:33:08.660695Z
false
linera-io/linera-protocol
https://github.com/linera-io/linera-protocol/blob/69f159d2106f7fc70870ce70074c55850bf1303b/examples/rfq/src/state.rs
examples/rfq/src/state.rs
// Copyright (c) Zefchain Labs, Inc. // SPDX-License-Identifier: Apache-2.0 use async_graphql::{InputObject, SimpleObject, Union}; use linera_sdk::{ linera_base_types::{AccountOwner, Amount, ChainId}, views::{linera_views, MapView, RegisterView, RootView, ViewStorageContext}, }; use rfq::{RequestId, TokenPair, Tokens}; use serde::{Deserialize, Serialize}; #[derive(Clone, Debug, Serialize, Deserialize, SimpleObject, InputObject)] #[graphql(input_name = "QuoteRequestedInput")] pub struct QuoteRequested { token_pair: TokenPair, amount: Amount, } #[derive(Clone, Debug, Serialize, Deserialize, SimpleObject, InputObject)] #[graphql(input_name = "QuoteProvidedInput")] pub struct QuoteProvided { token_pair: TokenPair, amount: Amount, amount_offered: Amount, quoter_owner: AccountOwner, } impl QuoteProvided { pub fn get_quoter_owner(&self) -> AccountOwner { self.quoter_owner } pub fn get_amount(&self) -> Amount { self.amount } } #[derive(Clone, Debug, Serialize, Deserialize, SimpleObject, InputObject)] #[graphql(input_name = "ExchangeInProgressInput")] pub struct ExchangeInProgress { temp_chain_id: ChainId, } #[derive(Clone, Debug, Serialize, Deserialize, SimpleObject, InputObject)] #[graphql(input_name = "AwaitingTokensInput")] pub struct AwaitingTokens { pub token_pair: TokenPair, pub amount_offered: Amount, pub quoter_account: AccountOwner, pub temp_chain_id: ChainId, } #[derive(Clone, Debug, Serialize, Deserialize, Union)] pub enum RequestState { QuoteRequested(QuoteRequested), QuoteProvided(QuoteProvided), AwaitingTokens(Box<AwaitingTokens>), ExchangeInProgress(ExchangeInProgress), } impl RequestState { fn token_pair(&self) -> TokenPair { match self { RequestState::QuoteRequested(QuoteRequested { token_pair, .. }) | RequestState::QuoteProvided(QuoteProvided { token_pair, .. }) => token_pair.clone(), _ => panic!("invalid state for reading the token pair"), } } } #[derive(Clone, Debug, Serialize, Deserialize, SimpleObject)] pub struct RequestData { state: RequestState, } #[derive(Clone, Debug, Serialize, Deserialize, SimpleObject)] pub struct TempChainTokenHolder { pub account_owner: AccountOwner, pub chain_id: ChainId, } #[derive(Clone, Debug, Serialize, Deserialize, SimpleObject)] pub struct TempChainState { request_id: RequestId, initiator: ChainId, token_pair: TokenPair, tokens_in_hold: Option<Tokens>, } #[derive(RootView, SimpleObject)] #[view(context = ViewStorageContext)] pub struct RfqState { next_seq_number: RegisterView<u64>, requests: MapView<RequestId, RequestData>, temp_chain_state: RegisterView<Option<TempChainState>>, } impl RequestData { pub fn update_state_with_quote(&mut self, quote: Amount, quoter_owner: AccountOwner) { match &self.state { RequestState::QuoteRequested(QuoteRequested { token_pair, amount }) => { self.state = RequestState::QuoteProvided(QuoteProvided { token_pair: token_pair.clone(), amount: *amount, amount_offered: quote, quoter_owner, }); } _ => panic!("Request not in the QuoteRequested state!"), } } pub fn quote_provided(&self) -> QuoteProvided { match &self.state { RequestState::QuoteProvided(quote_provided) => quote_provided.clone(), _ => panic!("Request not in the QuoteProvided state!"), } } pub fn start_exchange(&mut self, temp_chain_id: ChainId) { match &self.state { RequestState::QuoteProvided(_) | RequestState::AwaitingTokens(_) => { self.state = RequestState::ExchangeInProgress(ExchangeInProgress { temp_chain_id }); } _ => panic!("Request not in the QuoteProvided or AwaitingTokens state!"), } } pub fn accept_quote(&mut self, temp_chain_id: ChainId) { match &self.state { RequestState::QuoteProvided(QuoteProvided { token_pair, amount_offered, quoter_owner, .. }) => { self.state = RequestState::AwaitingTokens(Box::new(AwaitingTokens { token_pair: token_pair.clone(), amount_offered: *amount_offered, quoter_account: *quoter_owner, temp_chain_id, })); } _ => panic!("Request not in the QuoteProvided state!"), } } pub fn awaiting_tokens(&self) -> AwaitingTokens { match &self.state { RequestState::AwaitingTokens(awaiting_tokens) => (**awaiting_tokens).clone(), _ => panic!("Request not in the AwaitingTokens state!"), } } pub fn token_pair(&self) -> TokenPair { self.state.token_pair() } } impl RfqState { pub fn create_new_request( &mut self, target: ChainId, token_pair: TokenPair, amount: Amount, ) -> u64 { let seq_number = *self.next_seq_number.get(); let request_state = RequestState::QuoteRequested(QuoteRequested { token_pair, amount }); self.requests .insert( &RequestId::new(target, seq_number, true), RequestData { state: request_state, }, ) .expect("Couldn't insert a new request state"); self.next_seq_number.set(seq_number + 1); seq_number } pub fn register_request( &mut self, request_id: RequestId, token_pair: TokenPair, amount: Amount, ) { self.requests .insert( &request_id.with_we_requested(false), RequestData { state: RequestState::QuoteRequested(QuoteRequested { token_pair, amount }), }, ) .expect("Couldn't insert a new request state"); } pub async fn cancel_request(&mut self, request_id: &RequestId) -> Option<ChainId> { let req_data = self .requests .get(request_id) .await .expect("ViewError") .expect("Request not found"); match req_data.state { RequestState::ExchangeInProgress(ExchangeInProgress { temp_chain_id }) if request_id.is_our_request() => { Some(temp_chain_id) } _ => { self.requests.remove(request_id).expect("Request not found"); None } } } pub async fn close_request(&mut self, request_id: &RequestId) { self.requests.remove(request_id).expect("Request not found"); } pub async fn request_data(&mut self, request_id: &RequestId) -> Option<&mut RequestData> { self.requests.get_mut(request_id).await.expect("ViewError") } pub fn init_temp_chain_state( &mut self, request_id: RequestId, initiator: ChainId, token_pair: TokenPair, sent_tokens: Tokens, ) { self.temp_chain_state.set(Some(TempChainState { request_id, initiator, token_pair, tokens_in_hold: Some(sent_tokens), })); } pub fn is_temp_chain(&self) -> bool { self.temp_chain_state.get().is_some() } pub fn temp_chain_held_tokens(&self) -> Option<Tokens> { self.temp_chain_state .get() .as_ref() .and_then(|temp_state| temp_state.tokens_in_hold.clone()) } pub fn take_temp_chain_held_tokens(&mut self) -> Option<Tokens> { self.temp_chain_state .get_mut() .as_mut() .and_then(|temp_state| temp_state.tokens_in_hold.take()) } pub fn temp_chain_initiator_and_request_id(&self) -> (ChainId, RequestId) { let temp_chain_state = self .temp_chain_state .get() .as_ref() .expect("No TempChainState found!"); ( temp_chain_state.initiator, temp_chain_state.request_id.clone(), ) } }
rust
Apache-2.0
69f159d2106f7fc70870ce70074c55850bf1303b
2026-01-04T15:33:08.660695Z
false
linera-io/linera-protocol
https://github.com/linera-io/linera-protocol/blob/69f159d2106f7fc70870ce70074c55850bf1303b/examples/rfq/src/service.rs
examples/rfq/src/service.rs
// Copyright (c) Zefchain Labs, Inc. // SPDX-License-Identifier: Apache-2.0 #![cfg_attr(target_arch = "wasm32", no_main)] #[allow(unused)] mod state; use std::sync::Arc; use async_graphql::{EmptySubscription, Request, Response, Schema}; use linera_sdk::{ graphql::GraphQLMutationRoot as _, linera_base_types::WithServiceAbi, views::View, Service, ServiceRuntime, }; use rfq::Operation; use self::state::RfqState; pub struct RfqService { state: Arc<RfqState>, runtime: Arc<ServiceRuntime<Self>>, } linera_sdk::service!(RfqService); impl WithServiceAbi for RfqService { type Abi = rfq::RfqAbi; } impl Service for RfqService { type Parameters = (); async fn new(runtime: ServiceRuntime<Self>) -> Self { let state = RfqState::load(runtime.root_view_storage_context()) .await .expect("Failed to load state"); RfqService { state: Arc::new(state), runtime: Arc::new(runtime), } } async fn handle_query(&self, request: Request) -> Response { let schema = Schema::build( self.state.clone(), Operation::mutation_root(self.runtime.clone()), EmptySubscription, ) .finish(); schema.execute(request).await } }
rust
Apache-2.0
69f159d2106f7fc70870ce70074c55850bf1303b
2026-01-04T15:33:08.660695Z
false
linera-io/linera-protocol
https://github.com/linera-io/linera-protocol/blob/69f159d2106f7fc70870ce70074c55850bf1303b/examples/counter-no-graphql/src/contract.rs
examples/counter-no-graphql/src/contract.rs
// Copyright (c) Zefchain Labs, Inc. // SPDX-License-Identifier: Apache-2.0 #![cfg_attr(target_arch = "wasm32", no_main)] mod state; use counter_no_graphql::{CounterNoGraphQlAbi, CounterOperation}; use linera_sdk::{ linera_base_types::WithContractAbi, views::{RootView, View}, Contract, ContractRuntime, }; use self::state::CounterState; pub struct CounterContract { state: CounterState, runtime: ContractRuntime<Self>, } linera_sdk::contract!(CounterContract); impl WithContractAbi for CounterContract { type Abi = CounterNoGraphQlAbi; } impl Contract for CounterContract { type Message = (); type InstantiationArgument = u64; type Parameters = (); type EventValue = (); async fn load(runtime: ContractRuntime<Self>) -> Self { let state = CounterState::load(runtime.root_view_storage_context()) .await .expect("Failed to load state"); CounterContract { state, runtime } } async fn instantiate(&mut self, value: u64) { // Validate that the application parameters were configured correctly. self.runtime.application_parameters(); self.state.value.set(value); } async fn execute_operation(&mut self, operation: CounterOperation) -> u64 { let previous_value = self.state.value.get(); let CounterOperation::Increment(value) = operation; let new_value = previous_value + value; self.state.value.set(new_value); new_value } async fn execute_message(&mut self, _message: ()) { panic!("Counter application doesn't support any cross-chain messages"); } async fn store(mut self) { self.state.save().await.expect("Failed to save state"); } } #[cfg(test)] mod tests { use futures::FutureExt as _; use linera_sdk::{util::BlockingWait, views::View, Contract, ContractRuntime}; use super::{CounterContract, CounterOperation, CounterState}; #[test] fn operation() { let initial_value = 72_u64; let mut counter = create_and_instantiate_counter(initial_value); let increment = 42_308_u64; let operation = CounterOperation::Increment(increment); let response = counter .execute_operation(operation) .now_or_never() .expect("Execution of counter operation should not await anything"); let expected_value = initial_value + increment; assert_eq!(response, expected_value); assert_eq!(*counter.state.value.get(), initial_value + increment); } #[test] #[should_panic(expected = "Counter application doesn't support any cross-chain messages")] fn message() { let initial_value = 72_u64; let mut counter = create_and_instantiate_counter(initial_value); counter .execute_message(()) .now_or_never() .expect("Execution of counter operation should not await anything"); } #[test] fn cross_application_call() { let initial_value = 2_845_u64; let mut counter = create_and_instantiate_counter(initial_value); let increment = 8_u64; let operation = CounterOperation::Increment(increment); let response = counter .execute_operation(operation) .now_or_never() .expect("Execution of counter operation should not await anything"); let expected_value = initial_value + increment; assert_eq!(response, expected_value); assert_eq!(*counter.state.value.get(), expected_value); } fn create_and_instantiate_counter(initial_value: u64) -> CounterContract { let runtime = ContractRuntime::new().with_application_parameters(()); let mut contract = CounterContract { state: CounterState::load(runtime.root_view_storage_context()) .blocking_wait() .expect("Failed to read from mock key value store"), runtime, }; contract .instantiate(initial_value) .now_or_never() .expect("Initialization of counter state should not await anything"); assert_eq!(*contract.state.value.get(), initial_value); contract } }
rust
Apache-2.0
69f159d2106f7fc70870ce70074c55850bf1303b
2026-01-04T15:33:08.660695Z
false
linera-io/linera-protocol
https://github.com/linera-io/linera-protocol/blob/69f159d2106f7fc70870ce70074c55850bf1303b/examples/counter-no-graphql/src/lib.rs
examples/counter-no-graphql/src/lib.rs
// Copyright (c) Zefchain Labs, Inc. // SPDX-License-Identifier: Apache-2.0 /*! ABI of the Counter Example Application that does not use GraphQL */ use linera_sdk::linera_base_types::{ContractAbi, ServiceAbi}; use serde::{Deserialize, Serialize}; pub struct CounterNoGraphQlAbi; impl ContractAbi for CounterNoGraphQlAbi { type Operation = CounterOperation; type Response = u64; } impl ServiceAbi for CounterNoGraphQlAbi { type Query = CounterRequest; type QueryResponse = u64; } #[derive(Debug, Serialize, Deserialize)] pub enum CounterRequest { Query, Increment(u64), } #[derive(Debug, Serialize, Deserialize)] pub enum CounterOperation { Increment(u64), }
rust
Apache-2.0
69f159d2106f7fc70870ce70074c55850bf1303b
2026-01-04T15:33:08.660695Z
false
linera-io/linera-protocol
https://github.com/linera-io/linera-protocol/blob/69f159d2106f7fc70870ce70074c55850bf1303b/examples/counter-no-graphql/src/state.rs
examples/counter-no-graphql/src/state.rs
// Copyright (c) Zefchain Labs, Inc. // SPDX-License-Identifier: Apache-2.0 use linera_sdk::views::{linera_views, RegisterView, RootView, ViewStorageContext}; /// The application state. #[derive(RootView)] #[view(context = ViewStorageContext)] pub struct CounterState { pub value: RegisterView<u64>, }
rust
Apache-2.0
69f159d2106f7fc70870ce70074c55850bf1303b
2026-01-04T15:33:08.660695Z
false
linera-io/linera-protocol
https://github.com/linera-io/linera-protocol/blob/69f159d2106f7fc70870ce70074c55850bf1303b/examples/counter-no-graphql/src/service.rs
examples/counter-no-graphql/src/service.rs
// Copyright (c) Zefchain Labs, Inc. // SPDX-License-Identifier: Apache-2.0 #![cfg_attr(target_arch = "wasm32", no_main)] mod state; use std::sync::Arc; use counter_no_graphql::{CounterOperation, CounterRequest}; use linera_sdk::{linera_base_types::WithServiceAbi, views::View, Service, ServiceRuntime}; use self::state::CounterState; pub struct CounterService { state: CounterState, runtime: Arc<ServiceRuntime<Self>>, } linera_sdk::service!(CounterService); impl WithServiceAbi for CounterService { type Abi = counter_no_graphql::CounterNoGraphQlAbi; } impl Service for CounterService { type Parameters = (); async fn new(runtime: ServiceRuntime<Self>) -> Self { let state = CounterState::load(runtime.root_view_storage_context()) .await .expect("Failed to load state"); CounterService { state, runtime: Arc::new(runtime), } } async fn handle_query(&self, request: CounterRequest) -> u64 { // Load chain_id and application_creator_chain_id for comparison let chain_id = self.runtime.chain_id(); let application_creator_chain_id = self.runtime.application_creator_chain_id(); // Check that they are equal (for demonstration purposes) assert_eq!( chain_id, application_creator_chain_id, "Chain ID and Application Creator Chain ID should be equal" ); match request { CounterRequest::Query => *self.state.value.get(), CounterRequest::Increment(value) => { let operation = CounterOperation::Increment(value); self.runtime.schedule_operation(&operation); 0 } } } } #[cfg(test)] mod tests { use std::sync::Arc; use futures::FutureExt as _; use linera_sdk::{ linera_base_types::{ChainId, CryptoHash}, util::BlockingWait, views::View, Service, ServiceRuntime, }; use super::{CounterRequest, CounterService, CounterState}; #[test] fn query() { let value = 61_098_721_u64; let runtime = Arc::new(ServiceRuntime::<CounterService>::new()); let hash = ChainId(CryptoHash::test_hash("test")); runtime.set_chain_id(hash); runtime.set_application_creator_chain_id(hash); let mut state = CounterState::load(runtime.root_view_storage_context()) .blocking_wait() .expect("Failed to read from mock key value store"); state.value.set(value); let service = CounterService { state, runtime }; let request = CounterRequest::Query; let response = service .handle_query(request) .now_or_never() .expect("Query should not await anything"); assert_eq!(response, value) } }
rust
Apache-2.0
69f159d2106f7fc70870ce70074c55850bf1303b
2026-01-04T15:33:08.660695Z
false
linera-io/linera-protocol
https://github.com/linera-io/linera-protocol/blob/69f159d2106f7fc70870ce70074c55850bf1303b/examples/native-fungible/src/contract.rs
examples/native-fungible/src/contract.rs
// Copyright (c) Zefchain Labs, Inc. // SPDX-License-Identifier: Apache-2.0 #![cfg_attr(target_arch = "wasm32", no_main)] use linera_sdk::{ abis::fungible::{ FungibleOperation, FungibleResponse, FungibleTokenAbi, InitialState, Parameters, }, linera_base_types::{Account, AccountOwner, ChainId, WithContractAbi}, Contract, ContractRuntime, }; use native_fungible::{Message, TICKER_SYMBOL}; pub struct NativeFungibleTokenContract { runtime: ContractRuntime<Self>, } linera_sdk::contract!(NativeFungibleTokenContract); impl WithContractAbi for NativeFungibleTokenContract { type Abi = FungibleTokenAbi; } impl Contract for NativeFungibleTokenContract { type Message = Message; type Parameters = Parameters; type InstantiationArgument = InitialState; type EventValue = (); async fn load(runtime: ContractRuntime<Self>) -> Self { NativeFungibleTokenContract { runtime } } async fn instantiate(&mut self, state: Self::InstantiationArgument) { // Validate that the application parameters were configured correctly. assert!( self.runtime.application_parameters().ticker_symbol == "NAT", "Only NAT is accepted as ticker symbol" ); for (owner, amount) in state.accounts { let account = Account { chain_id: self.runtime.chain_id(), owner, }; self.runtime.transfer(AccountOwner::CHAIN, account, amount); } } async fn execute_operation(&mut self, operation: Self::Operation) -> Self::Response { match operation { FungibleOperation::Balance { owner } => { log::info!("balance check for owner={}", owner); let balance = self.runtime.owner_balance(owner); FungibleResponse::Balance(balance) } FungibleOperation::TickerSymbol => { FungibleResponse::TickerSymbol(String::from(TICKER_SYMBOL)) } FungibleOperation::Approve { .. } => { panic!("Approve operation is not supported by native fungible token") } FungibleOperation::Transfer { owner, amount, target_account, } => { self.runtime .check_account_permission(owner) .expect("Permission for Transfer operation"); let fungible_target_account = target_account; let target_account = self.normalize_account(target_account); log::info!( "transferring tokens from={} to={} amount={}", owner, target_account.owner, amount ); self.runtime.transfer(owner, target_account, amount); self.transfer(fungible_target_account.chain_id); FungibleResponse::Ok } FungibleOperation::TransferFrom { .. } => { panic!("TransferFrom operation is not supported by native fungible token") } FungibleOperation::Claim { source_account, amount, target_account, } => { self.runtime .check_account_permission(source_account.owner) .expect("Permission for Claim operation"); let fungible_source_account = source_account; let fungible_target_account = target_account; let source_account = self.normalize_account(source_account); let target_account = self.normalize_account(target_account); self.runtime.claim(source_account, target_account, amount); self.claim( fungible_source_account.chain_id, fungible_target_account.chain_id, ); FungibleResponse::Ok } } } async fn execute_message(&mut self, message: Self::Message) { // Messages for now don't do anything, just pass messages around match message { Message::Notify => (), } } async fn store(self) {} } impl NativeFungibleTokenContract { fn transfer(&mut self, chain_id: ChainId) { if chain_id != self.runtime.chain_id() { let message = Message::Notify; self.runtime .prepare_message(message) .with_authentication() .send_to(chain_id); } } fn claim(&mut self, source_chain_id: ChainId, target_chain_id: ChainId) { if source_chain_id == self.runtime.chain_id() { self.transfer(target_chain_id); } else { // If different chain, send notify message so the app gets auto-deployed let message = Message::Notify; self.runtime .prepare_message(message) .with_authentication() .send_to(source_chain_id); } } fn normalize_account(&self, account: Account) -> Account { Account { chain_id: account.chain_id, owner: account.owner, } } }
rust
Apache-2.0
69f159d2106f7fc70870ce70074c55850bf1303b
2026-01-04T15:33:08.660695Z
false
linera-io/linera-protocol
https://github.com/linera-io/linera-protocol/blob/69f159d2106f7fc70870ce70074c55850bf1303b/examples/native-fungible/src/lib.rs
examples/native-fungible/src/lib.rs
// Copyright (c) Zefchain Labs, Inc. // SPDX-License-Identifier: Apache-2.0 /*! ABI of the Native Fungible Token Example Application */ use async_graphql::SimpleObject; use linera_sdk::linera_base_types::{AccountOwner, Amount}; use serde::{Deserialize, Serialize}; pub const TICKER_SYMBOL: &str = "NAT"; #[derive(Deserialize, SimpleObject)] pub struct AccountEntry { pub key: AccountOwner, pub value: Amount, } #[derive(Debug, Deserialize, Serialize)] pub enum Message { Notify, }
rust
Apache-2.0
69f159d2106f7fc70870ce70074c55850bf1303b
2026-01-04T15:33:08.660695Z
false
linera-io/linera-protocol
https://github.com/linera-io/linera-protocol/blob/69f159d2106f7fc70870ce70074c55850bf1303b/examples/native-fungible/src/service.rs
examples/native-fungible/src/service.rs
// Copyright (c) Zefchain Labs, Inc. // SPDX-License-Identifier: Apache-2.0 #![cfg_attr(target_arch = "wasm32", no_main)] use std::sync::Arc; use async_graphql::{EmptySubscription, Object, Request, Response, Schema}; use fungible::Parameters; use linera_sdk::{ abis::fungible::{FungibleOperation, FungibleTokenAbi}, graphql::GraphQLMutationRoot as _, linera_base_types::{AccountOwner, WithServiceAbi}, Service, ServiceRuntime, }; use native_fungible::{AccountEntry, TICKER_SYMBOL}; #[derive(Clone)] pub struct NativeFungibleTokenService { runtime: Arc<ServiceRuntime<Self>>, } linera_sdk::service!(NativeFungibleTokenService); impl WithServiceAbi for NativeFungibleTokenService { type Abi = FungibleTokenAbi; } impl Service for NativeFungibleTokenService { type Parameters = Parameters; async fn new(runtime: ServiceRuntime<Self>) -> Self { NativeFungibleTokenService { runtime: Arc::new(runtime), } } async fn handle_query(&self, request: Request) -> Response { let schema = Schema::build( self.clone(), FungibleOperation::mutation_root(self.runtime.clone()), EmptySubscription, ) .finish(); schema.execute(request).await } } struct Accounts { runtime: Arc<ServiceRuntime<NativeFungibleTokenService>>, } #[Object] impl Accounts { // Define a field that lets you query by key async fn entry(&self, key: AccountOwner) -> AccountEntry { let value = self.runtime.owner_balance(key); AccountEntry { key, value } } async fn entries(&self) -> Vec<AccountEntry> { self.runtime .owner_balances() .into_iter() .map(|(owner, amount)| AccountEntry { key: owner, value: amount, }) .collect() } async fn keys(&self) -> Vec<AccountOwner> { self.runtime.balance_owners() } } // Implements additional fields not derived from struct members of FungibleToken. #[Object] impl NativeFungibleTokenService { async fn ticker_symbol(&self) -> Result<String, async_graphql::Error> { Ok(String::from(TICKER_SYMBOL)) } async fn accounts(&self) -> Result<Accounts, async_graphql::Error> { Ok(Accounts { runtime: self.runtime.clone(), }) } }
rust
Apache-2.0
69f159d2106f7fc70870ce70074c55850bf1303b
2026-01-04T15:33:08.660695Z
false
linera-io/linera-protocol
https://github.com/linera-io/linera-protocol/blob/69f159d2106f7fc70870ce70074c55850bf1303b/examples/native-fungible/tests/transfers.rs
examples/native-fungible/tests/transfers.rs
// Copyright (c) Zefchain Labs, Inc. // SPDX-License-Identifier: Apache-2.0 #![cfg(not(target_arch = "wasm32"))] //! Integration tests for Native Fungible Token transfers. use std::collections::{BTreeMap, HashMap}; use fungible::{self, FungibleTokenAbi}; use linera_sdk::{ linera_base_types::{Account, AccountOwner, Amount, CryptoHash}, test::{ActiveChain, TestValidator}, }; /// Tests if tokens from the shared chain balance can be sent to a different chain. #[test_log::test(tokio::test)] async fn chain_balance_transfers() { let parameters = fungible::Parameters { ticker_symbol: "NAT".to_owned(), }; let initial_state = fungible::InitialStateBuilder::default().build(); let (validator, _application_id, recipient_chain) = TestValidator::with_current_application::< FungibleTokenAbi, _, _, >(parameters, initial_state) .await; let transfer_amount = Amount::ONE; let funding_chain = validator.get_chain(&validator.admin_chain_id()); let recipient = Account::chain(recipient_chain.id()); let transfer_certificate = funding_chain .add_block(|block| { block.with_native_token_transfer(AccountOwner::CHAIN, recipient, transfer_amount); }) .await; recipient_chain .add_block(|block| { block.with_messages_from(&transfer_certificate); }) .await; // At the start, chain has balance of 10 tokens. // After the transfer, it should have 11 tokens. let expected_balance = Amount::from_tokens(10) + transfer_amount; assert_eq!(recipient_chain.chain_balance().await, expected_balance); assert_balances(&recipient_chain, []).await; } /// Tests if an individual account can receive tokens. #[test_log::test(tokio::test)] async fn transfer_to_owner() { let parameters = fungible::Parameters { ticker_symbol: "NAT".to_owned(), }; let initial_state = fungible::InitialStateBuilder::default().build(); let (validator, _application_id, recipient_chain) = TestValidator::with_current_application::< FungibleTokenAbi, _, _, >(parameters, initial_state) .await; let transfer_amount = Amount::from_tokens(2); let funding_chain = validator.get_chain(&validator.admin_chain_id()); let owner = AccountOwner::from(CryptoHash::test_hash("owner")); let recipient = Account::new(recipient_chain.id(), owner); let transfer_certificate = funding_chain .add_block(|block| { block.with_native_token_transfer(AccountOwner::CHAIN, recipient, transfer_amount); }) .await; recipient_chain .add_block(|block| { block.with_messages_from(&transfer_certificate); }) .await; assert_balances(&recipient_chain, [(owner, transfer_amount)]).await; } /// Tests if multiple accounts can receive tokens. #[test_log::test(tokio::test)] async fn transfer_to_multiple_owners() { let parameters = fungible::Parameters { ticker_symbol: "NAT".to_owned(), }; let initial_state = fungible::InitialStateBuilder::default().build(); let (validator, _application_id, recipient_chain) = TestValidator::with_current_application::< FungibleTokenAbi, _, _, >(parameters, initial_state) .await; let number_of_owners = 10; let transfer_amounts = (1..=number_of_owners).map(Amount::from_tokens); let funding_chain = validator.get_chain(&validator.admin_chain_id()); let account_owners = (1..=number_of_owners) .map(|index| AccountOwner::from(CryptoHash::test_hash(format!("owner{index}")))) .collect::<Vec<_>>(); let recipients = account_owners .iter() .copied() .map(|account_owner| Account::new(recipient_chain.id(), account_owner)); let transfer_certificate = funding_chain .add_block(|block| { for (recipient, transfer_amount) in recipients.zip(transfer_amounts.clone()) { block.with_native_token_transfer(AccountOwner::CHAIN, recipient, transfer_amount); } }) .await; recipient_chain .add_block(|block| { block.with_messages_from(&transfer_certificate); }) .await; assert_balances( &recipient_chain, account_owners.into_iter().zip(transfer_amounts), ) .await; } /// Tests if an account that was emptied out doesn't appear in balance queries. #[test_log::test(tokio::test)] async fn emptied_account_disappears_from_queries() { let parameters = fungible::Parameters { ticker_symbol: "NAT".to_owned(), }; let initial_state = fungible::InitialStateBuilder::default().build(); let (validator, _application_id, recipient_chain) = TestValidator::with_current_application::< FungibleTokenAbi, _, _, >(parameters, initial_state) .await; let transfer_amount = Amount::from_tokens(100); let funding_chain = validator.get_chain(&validator.admin_chain_id()); let owner = AccountOwner::from(recipient_chain.public_key()); let recipient = Account::new(recipient_chain.id(), owner); let transfer_certificate = funding_chain .add_block(|block| { block.with_native_token_transfer(AccountOwner::CHAIN, recipient, transfer_amount); }) .await; recipient_chain .add_block(|block| { block.with_messages_from(&transfer_certificate); }) .await; recipient_chain .add_block(|block| { block.with_native_token_transfer( owner, Account::chain(recipient_chain.id()), transfer_amount, ); }) .await; assert_eq!(recipient_chain.owner_balance(&owner).await, None); assert_balances(&recipient_chain, []).await; } /// Asserts that all the accounts in the [`ActiveChain`] have the `expected_balances`. async fn assert_balances( chain: &ActiveChain, expected_balances: impl IntoIterator<Item = (AccountOwner, Amount)>, ) { let expected_balances = expected_balances.into_iter().collect::<BTreeMap<_, _>>(); let accounts = expected_balances.keys().copied().collect::<Vec<_>>(); assert_eq!(chain.accounts().await, accounts); let missing_accounts = ["missing1", "missing2"] .into_iter() .map(CryptoHash::test_hash) .map(AccountOwner::from) .collect::<Vec<_>>(); let accounts_to_query = accounts .into_iter() .chain(missing_accounts.iter().copied()) .collect::<Vec<_>>(); let expected_query_response = expected_balances .iter() .map(|(&account, &balance)| (account, Some(balance))) .chain(missing_accounts.into_iter().map(|account| (account, None))) .collect::<HashMap<_, _>>(); for account in &accounts_to_query { assert_eq!( &chain.owner_balance(account).await, expected_query_response .get(account) .expect("Missing balance amount for a test account") ); } assert_eq!( chain.owner_balances(accounts_to_query).await, expected_query_response ); assert_eq!( chain.all_owner_balances().await, HashMap::from_iter(expected_balances) ); }
rust
Apache-2.0
69f159d2106f7fc70870ce70074c55850bf1303b
2026-01-04T15:33:08.660695Z
false
linera-io/linera-protocol
https://github.com/linera-io/linera-protocol/blob/69f159d2106f7fc70870ce70074c55850bf1303b/examples/task-processor/src/contract.rs
examples/task-processor/src/contract.rs
// Copyright (c) Zefchain Labs, Inc. // SPDX-License-Identifier: Apache-2.0 #![cfg_attr(target_arch = "wasm32", no_main)] mod state; use linera_sdk::{ linera_base_types::WithContractAbi, views::{RootView, View}, Contract, ContractRuntime, }; use task_processor::{TaskProcessorAbi, TaskProcessorOperation}; use self::state::{PendingTask, TaskProcessorState}; pub struct TaskProcessorContract { state: TaskProcessorState, runtime: ContractRuntime<Self>, } linera_sdk::contract!(TaskProcessorContract); impl WithContractAbi for TaskProcessorContract { type Abi = TaskProcessorAbi; } impl Contract for TaskProcessorContract { type Message = (); type InstantiationArgument = (); type Parameters = (); type EventValue = (); async fn load(runtime: ContractRuntime<Self>) -> Self { let state = TaskProcessorState::load(runtime.root_view_storage_context()) .await .expect("Failed to load state"); TaskProcessorContract { state, runtime } } async fn instantiate(&mut self, _argument: ()) { self.runtime.application_parameters(); } async fn execute_operation(&mut self, operation: TaskProcessorOperation) { match operation { TaskProcessorOperation::RequestTask { operator, input } => { self.state .pending_tasks .push_back(PendingTask { operator, input }); } TaskProcessorOperation::StoreResult { result } => { // Remove the first pending task (the one that was just processed). self.state.pending_tasks.delete_front(); self.state.results.push_back(result); let count = self.state.task_count.get() + 1; self.state.task_count.set(count); } } } async fn execute_message(&mut self, _message: ()) { panic!("Task processor application doesn't support any cross-chain messages"); } async fn store(mut self) { self.state.save().await.expect("Failed to save state"); } }
rust
Apache-2.0
69f159d2106f7fc70870ce70074c55850bf1303b
2026-01-04T15:33:08.660695Z
false
linera-io/linera-protocol
https://github.com/linera-io/linera-protocol/blob/69f159d2106f7fc70870ce70074c55850bf1303b/examples/task-processor/src/lib.rs
examples/task-processor/src/lib.rs
// Copyright (c) Zefchain Labs, Inc. // SPDX-License-Identifier: Apache-2.0 //! ABI of the Task Processor Example Application. //! //! This application demonstrates the off-chain task processor functionality. //! It requests tasks to be executed by an external "echo" operator and stores //! the results in its state. use async_graphql::{Request, Response}; use linera_sdk::linera_base_types::{ContractAbi, ServiceAbi}; use serde::{Deserialize, Serialize}; pub struct TaskProcessorAbi; /// Operations that can be executed on the contract. #[derive(Debug, Deserialize, Serialize)] pub enum TaskProcessorOperation { /// Request a task to be processed by the given operator with the given input. RequestTask { operator: String, input: String }, /// Store the result of a completed task. StoreResult { result: String }, } impl ContractAbi for TaskProcessorAbi { type Operation = TaskProcessorOperation; type Response = (); } impl ServiceAbi for TaskProcessorAbi { type Query = Request; type QueryResponse = Response; }
rust
Apache-2.0
69f159d2106f7fc70870ce70074c55850bf1303b
2026-01-04T15:33:08.660695Z
false
linera-io/linera-protocol
https://github.com/linera-io/linera-protocol/blob/69f159d2106f7fc70870ce70074c55850bf1303b/examples/task-processor/src/state.rs
examples/task-processor/src/state.rs
// Copyright (c) Zefchain Labs, Inc. // SPDX-License-Identifier: Apache-2.0 use linera_sdk::views::{linera_views, QueueView, RegisterView, RootView, ViewStorageContext}; use serde::{Deserialize, Serialize}; /// A pending task stored in the application state. #[derive(Clone, Debug, Serialize, Deserialize, async_graphql::SimpleObject)] pub struct PendingTask { /// The operator to execute the task. pub operator: String, /// The input to pass to the operator. pub input: String, } /// The application state. #[derive(RootView, async_graphql::SimpleObject)] #[view(context = ViewStorageContext)] pub struct TaskProcessorState { /// Pending tasks to be executed. pub pending_tasks: QueueView<PendingTask>, /// Results from completed tasks. pub results: QueueView<String>, /// Counter for tracking how many tasks have been processed. pub task_count: RegisterView<u64>, }
rust
Apache-2.0
69f159d2106f7fc70870ce70074c55850bf1303b
2026-01-04T15:33:08.660695Z
false
linera-io/linera-protocol
https://github.com/linera-io/linera-protocol/blob/69f159d2106f7fc70870ce70074c55850bf1303b/examples/task-processor/src/service.rs
examples/task-processor/src/service.rs
// Copyright (c) Zefchain Labs, Inc. // SPDX-License-Identifier: Apache-2.0 #![cfg_attr(target_arch = "wasm32", no_main)] mod state; use std::sync::Arc; use async_graphql::{EmptySubscription, Object, Request, Response, Schema}; use linera_sdk::{ linera_base_types::{Timestamp, WithServiceAbi}, task_processor::{ProcessorActions, Task, TaskOutcome}, views::View, Service, ServiceRuntime, }; use task_processor::{TaskProcessorAbi, TaskProcessorOperation}; use self::state::TaskProcessorState; pub struct TaskProcessorService { state: Arc<TaskProcessorState>, runtime: Arc<ServiceRuntime<Self>>, } linera_sdk::service!(TaskProcessorService); impl WithServiceAbi for TaskProcessorService { type Abi = TaskProcessorAbi; } impl Service for TaskProcessorService { type Parameters = (); async fn new(runtime: ServiceRuntime<Self>) -> Self { let state = TaskProcessorState::load(runtime.root_view_storage_context()) .await .expect("Failed to load state"); TaskProcessorService { state: Arc::new(state), runtime: Arc::new(runtime), } } async fn handle_query(&self, request: Request) -> Response { let schema = Schema::build( QueryRoot { state: self.state.clone(), runtime: self.runtime.clone(), }, MutationRoot { runtime: self.runtime.clone(), }, EmptySubscription, ) .finish(); schema.execute(request).await } } struct QueryRoot { state: Arc<TaskProcessorState>, runtime: Arc<ServiceRuntime<TaskProcessorService>>, } #[Object] impl QueryRoot { /// Returns the current task count. async fn task_count(&self) -> u64 { *self.state.task_count.get() } /// Returns the pending tasks and callback requests for the task processor. async fn next_actions( &self, _last_requested_callback: Option<Timestamp>, _now: Timestamp, ) -> ProcessorActions { let mut actions = ProcessorActions::default(); // Get all pending tasks from the queue. let count = self.state.pending_tasks.count(); if let Ok(pending_tasks) = self.state.pending_tasks.read_front(count).await { for pending in pending_tasks { actions.execute_tasks.push(Task { operator: pending.operator, input: pending.input, }); } } actions } /// Processes the outcome of a completed task and schedules operations. async fn process_task_outcome(&self, outcome: TaskOutcome) -> bool { // Schedule an operation to store the result and remove the pending task. let operation = TaskProcessorOperation::StoreResult { result: outcome.output, }; self.runtime.schedule_operation(&operation); true } } struct MutationRoot { runtime: Arc<ServiceRuntime<TaskProcessorService>>, } #[Object] impl MutationRoot { /// Requests a task to be processed by an off-chain operator. async fn request_task(&self, operator: String, input: String) -> [u8; 0] { let operation = TaskProcessorOperation::RequestTask { operator, input }; self.runtime.schedule_operation(&operation); [] } }
rust
Apache-2.0
69f159d2106f7fc70870ce70074c55850bf1303b
2026-01-04T15:33:08.660695Z
false
linera-io/linera-protocol
https://github.com/linera-io/linera-protocol/blob/69f159d2106f7fc70870ce70074c55850bf1303b/examples/gen-nft/src/random.rs
examples/gen-nft/src/random.rs
// Copyright (c) Zefchain Labs, Inc. // SPDX-License-Identifier: Apache-2.0 use std::sync::{Mutex, OnceLock}; use rand::{rngs::StdRng, Rng, SeedableRng}; static RNG: OnceLock<Mutex<StdRng>> = OnceLock::new(); fn custom_getrandom(buf: &mut [u8]) -> Result<(), getrandom::Error> { let seed = [0u8; 32]; RNG.get_or_init(|| Mutex::new(StdRng::from_seed(seed))) .lock() .expect("failed to get RNG lock") .fill(buf); Ok(()) } getrandom::register_custom_getrandom!(custom_getrandom);
rust
Apache-2.0
69f159d2106f7fc70870ce70074c55850bf1303b
2026-01-04T15:33:08.660695Z
false
linera-io/linera-protocol
https://github.com/linera-io/linera-protocol/blob/69f159d2106f7fc70870ce70074c55850bf1303b/examples/gen-nft/src/contract.rs
examples/gen-nft/src/contract.rs
// Copyright (c) Zefchain Labs, Inc. // SPDX-License-Identifier: Apache-2.0 #![cfg_attr(target_arch = "wasm32", no_main)] mod state; use std::collections::BTreeSet; use gen_nft::{GenNftAbi, Message, Nft, Operation, TokenId}; use linera_sdk::{ linera_base_types::{Account, AccountOwner, WithContractAbi}, views::{RootView, View}, Contract, ContractRuntime, }; use self::state::GenNftState; pub struct GenNftContract { state: GenNftState, runtime: ContractRuntime<Self>, } linera_sdk::contract!(GenNftContract); impl WithContractAbi for GenNftContract { type Abi = GenNftAbi; } impl Contract for GenNftContract { type Message = Message; type InstantiationArgument = (); type Parameters = (); type EventValue = (); async fn load(runtime: ContractRuntime<Self>) -> Self { let state = GenNftState::load(runtime.root_view_storage_context()) .await .expect("Failed to load state"); GenNftContract { state, runtime } } async fn instantiate(&mut self, _state: Self::InstantiationArgument) { // Validate that the application parameters were configured correctly. self.runtime.application_parameters(); self.state.num_minted_nfts.set(0); } async fn execute_operation(&mut self, operation: Self::Operation) -> Self::Response { match operation { Operation::Mint { minter, prompt } => { self.runtime .check_account_permission(minter) .expect("Permission for Mint operation"); self.mint(minter, prompt).await; } Operation::Transfer { source_owner, token_id, target_account, } => { self.runtime .check_account_permission(source_owner) .expect("Permission for Transfer operation"); let nft = self.get_nft(&token_id).await; assert_eq!(source_owner, nft.owner); self.transfer(nft, target_account).await; } Operation::Claim { source_account, token_id, target_account, } => { self.runtime .check_account_permission(source_account.owner) .expect("Permission for Claim operation"); if source_account.chain_id == self.runtime.chain_id() { let nft = self.get_nft(&token_id).await; assert_eq!(source_account.owner, nft.owner); self.transfer(nft, target_account).await; } else { self.remote_claim(source_account, token_id, target_account) } } } } async fn execute_message(&mut self, message: Message) { match message { Message::Transfer { mut nft, target_account, } => { let is_bouncing = self .runtime .message_is_bouncing() .expect("Message delivery status has to be available when executing a message"); if !is_bouncing { nft.owner = target_account.owner; } self.add_nft(nft).await; } Message::Claim { source_account, token_id, target_account, } => { self.runtime .check_account_permission(source_account.owner) .expect("Permission for Claim message"); let nft = self.get_nft(&token_id).await; assert_eq!(source_account.owner, nft.owner); self.transfer(nft, target_account).await; } } } async fn store(mut self) { self.state.save().await.expect("Failed to save state"); } } impl GenNftContract { /// Transfers the specified NFT to another account. /// Authentication needs to have happened already. async fn transfer(&mut self, mut nft: Nft, target_account: Account) { self.remove_nft(&nft).await; if target_account.chain_id == self.runtime.chain_id() { nft.owner = target_account.owner; self.add_nft(nft).await; } else { let message = Message::Transfer { nft, target_account, }; self.runtime .prepare_message(message) .with_tracking() .send_to(target_account.chain_id); } } async fn get_nft(&self, token_id: &TokenId) -> Nft { self.state .nfts .get(token_id) .await .expect("Failure in retrieving NFT") .expect("NFT not found") } async fn mint(&mut self, owner: AccountOwner, prompt: String) { let token_id = Nft::create_token_id( &self.runtime.chain_id(), &self.runtime.application_id().forget_abi(), &prompt, &owner, *self.state.num_minted_nfts.get(), ) .expect("Failed to serialize NFT metadata"); self.add_nft(Nft { token_id, owner, prompt, minter: owner, }) .await; let num_minted_nfts = self.state.num_minted_nfts.get_mut(); *num_minted_nfts += 1; } fn remote_claim( &mut self, source_account: Account, token_id: TokenId, target_account: Account, ) { let message = Message::Claim { source_account, token_id, target_account, }; self.runtime .prepare_message(message) .with_authentication() .send_to(source_account.chain_id); } async fn add_nft(&mut self, nft: Nft) { let token_id = nft.token_id.clone(); let owner = nft.owner; self.state .nfts .insert(&token_id, nft) .expect("Error in insert statement"); if let Some(owned_token_ids) = self .state .owned_token_ids .get_mut(&owner) .await .expect("Error in get_mut statement") { owned_token_ids.insert(token_id); } else { let mut owned_token_ids = BTreeSet::new(); owned_token_ids.insert(token_id); self.state .owned_token_ids .insert(&owner, owned_token_ids) .expect("Error in insert statement"); } } async fn remove_nft(&mut self, nft: &Nft) { self.state .nfts .remove(&nft.token_id) .expect("Failed to remove NFT"); let owned_token_ids = self .state .owned_token_ids .get_mut(&nft.owner) .await .expect("Error in get_mut statement") .expect("NFT set should be there!"); owned_token_ids.remove(&nft.token_id); } }
rust
Apache-2.0
69f159d2106f7fc70870ce70074c55850bf1303b
2026-01-04T15:33:08.660695Z
false
linera-io/linera-protocol
https://github.com/linera-io/linera-protocol/blob/69f159d2106f7fc70870ce70074c55850bf1303b/examples/gen-nft/src/lib.rs
examples/gen-nft/src/lib.rs
// Copyright (c) Zefchain Labs, Inc. // SPDX-License-Identifier: Apache-2.0 /*! ABI of the Generative NFT Example Application */ use std::fmt::{Display, Formatter}; use async_graphql::{InputObject, Request, Response, SimpleObject}; use linera_sdk::{ linera_base_types::{Account, AccountOwner, ApplicationId, ChainId, ContractAbi, ServiceAbi}, ToBcsBytes, }; use serde::{Deserialize, Serialize}; #[derive( Debug, Serialize, Deserialize, Clone, PartialEq, Eq, Ord, PartialOrd, SimpleObject, InputObject, )] #[graphql(input_name = "TokenIdInput")] pub struct TokenId { pub id: Vec<u8>, } pub struct GenNftAbi; impl ContractAbi for GenNftAbi { type Operation = Operation; type Response = (); } impl ServiceAbi for GenNftAbi { type Query = Request; type QueryResponse = Response; } /// An operation. #[derive(Debug, Deserialize, Serialize)] pub enum Operation { /// Mints a token Mint { minter: AccountOwner, prompt: String, }, /// Transfers a token from a (locally owned) account to a (possibly remote) account. Transfer { source_owner: AccountOwner, token_id: TokenId, target_account: Account, }, /// Same as `Transfer` but the source account may be remote. Depending on its /// configuration, the target chain may take time or refuse to process /// the message. Claim { source_account: Account, token_id: TokenId, target_account: Account, }, } /// A message. #[derive(Debug, Deserialize, Serialize)] pub enum Message { /// Transfers to the given `target` account, unless the message is bouncing, in which case /// we transfer back to the `source`. Transfer { nft: Nft, target_account: Account }, /// Claims from the given account and starts a transfer to the target account. Claim { source_account: Account, token_id: TokenId, target_account: Account, }, } #[derive(Debug, Serialize, Deserialize, Clone, SimpleObject, PartialEq, Eq)] #[serde(rename_all = "camelCase")] pub struct Nft { pub token_id: TokenId, pub owner: AccountOwner, pub prompt: String, pub minter: AccountOwner, } #[derive(Debug, Serialize, Deserialize, Clone, SimpleObject, PartialEq, Eq)] #[serde(rename_all = "camelCase")] pub struct NftOutput { pub token_id: String, pub owner: AccountOwner, pub prompt: String, pub minter: AccountOwner, } impl NftOutput { pub fn new(nft: Nft) -> Self { use base64::engine::{general_purpose::STANDARD_NO_PAD, Engine as _}; let token_id = STANDARD_NO_PAD.encode(nft.token_id.id); Self { token_id, owner: nft.owner, prompt: nft.prompt, minter: nft.minter, } } pub fn new_with_token_id(token_id: String, nft: Nft) -> Self { Self { token_id, owner: nft.owner, prompt: nft.prompt, minter: nft.minter, } } } impl Display for TokenId { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { write!(f, "{:?}", self.id) } } impl Nft { pub fn create_token_id( chain_id: &ChainId, application_id: &ApplicationId, prompt: &String, minter: &AccountOwner, num_minted_nfts: u64, ) -> Result<TokenId, bcs::Error> { use sha3::Digest as _; let mut hasher = sha3::Sha3_256::new(); hasher.update(chain_id.to_bcs_bytes()?); hasher.update(application_id.to_bcs_bytes()?); hasher.update(prompt); hasher.update(minter.to_bcs_bytes()?); hasher.update(num_minted_nfts.to_bcs_bytes()?); Ok(TokenId { id: hasher.finalize().to_vec(), }) } }
rust
Apache-2.0
69f159d2106f7fc70870ce70074c55850bf1303b
2026-01-04T15:33:08.660695Z
false
linera-io/linera-protocol
https://github.com/linera-io/linera-protocol/blob/69f159d2106f7fc70870ce70074c55850bf1303b/examples/gen-nft/src/state.rs
examples/gen-nft/src/state.rs
// Copyright (c) Zefchain Labs, Inc. // SPDX-License-Identifier: Apache-2.0 use std::collections::BTreeSet; use async_graphql::SimpleObject; use gen_nft::{Nft, TokenId}; use linera_sdk::{ linera_base_types::AccountOwner, views::{linera_views, MapView, RegisterView, RootView, ViewStorageContext}, }; /// The application state. #[derive(RootView, SimpleObject)] #[view(context = ViewStorageContext)] pub struct GenNftState { // Map from token ID to the NFT data pub nfts: MapView<TokenId, Nft>, // Map from owners to the set of NFT token IDs they own pub owned_token_ids: MapView<AccountOwner, BTreeSet<TokenId>>, // Counter of NFTs minted in this chain, used for hash uniqueness pub num_minted_nfts: RegisterView<u64>, }
rust
Apache-2.0
69f159d2106f7fc70870ce70074c55850bf1303b
2026-01-04T15:33:08.660695Z
false
linera-io/linera-protocol
https://github.com/linera-io/linera-protocol/blob/69f159d2106f7fc70870ce70074c55850bf1303b/examples/gen-nft/src/service.rs
examples/gen-nft/src/service.rs
// Copyright (c) Zefchain Labs, Inc. // SPDX-License-Identifier: Apache-2.0 #![cfg_attr(target_arch = "wasm32", no_main)] mod model; mod random; mod state; mod token; use std::{ collections::{BTreeMap, BTreeSet}, sync::Arc, }; use async_graphql::{Context, EmptySubscription, Object, Request, Response, Schema}; use base64::engine::{general_purpose::STANDARD_NO_PAD, Engine as _}; use gen_nft::{NftOutput, Operation, TokenId}; use linera_sdk::{ http, linera_base_types::{Account, AccountOwner, WithServiceAbi}, views::View, Service, ServiceRuntime, }; use log::info; use self::state::GenNftState; use crate::model::ModelContext; pub struct GenNftService { state: Arc<GenNftState>, runtime: Arc<ServiceRuntime<Self>>, } linera_sdk::service!(GenNftService); impl WithServiceAbi for GenNftService { type Abi = gen_nft::GenNftAbi; } impl Service for GenNftService { type Parameters = (); async fn new(runtime: ServiceRuntime<Self>) -> Self { let state = GenNftState::load(runtime.root_view_storage_context()) .await .expect("Failed to load state"); GenNftService { state: Arc::new(state), runtime: Arc::new(runtime), } } async fn handle_query(&self, request: Request) -> Response { let runtime = self.runtime.clone(); let schema = Schema::build( QueryRoot { non_fungible_token: self.state.clone(), }, MutationRoot { runtime: self.runtime.clone(), }, EmptySubscription, ) .data(runtime) .finish(); schema.execute(request).await } } struct QueryRoot { non_fungible_token: Arc<GenNftState>, } #[Object] impl QueryRoot { async fn nft(&self, token_id: String) -> Option<NftOutput> { let token_id_vec = STANDARD_NO_PAD.decode(&token_id).unwrap(); let nft = self .non_fungible_token .nfts .get(&TokenId { id: token_id_vec }) .await .unwrap(); if let Some(nft) = nft { let nft_output = NftOutput::new_with_token_id(token_id, nft); Some(nft_output) } else { None } } async fn nfts(&self) -> BTreeMap<String, NftOutput> { let mut nfts = BTreeMap::new(); self.non_fungible_token .nfts .for_each_index_value(|_token_id, nft| { let nft = nft.into_owned(); let nft_output = NftOutput::new(nft); nfts.insert(nft_output.token_id.clone(), nft_output); Ok(()) }) .await .unwrap(); nfts } async fn owned_token_ids_by_owner(&self, owner: AccountOwner) -> BTreeSet<String> { self.non_fungible_token .owned_token_ids .get(&owner) .await .unwrap() .into_iter() .flatten() .map(|token_id| STANDARD_NO_PAD.encode(token_id.id)) .collect() } async fn owned_token_ids(&self) -> BTreeMap<AccountOwner, BTreeSet<String>> { let mut owners = BTreeMap::new(); self.non_fungible_token .owned_token_ids .for_each_index_value(|owner, token_ids| { let token_ids = token_ids.into_owned(); let new_token_ids = token_ids .into_iter() .map(|token_id| STANDARD_NO_PAD.encode(token_id.id)) .collect(); owners.insert(owner, new_token_ids); Ok(()) }) .await .unwrap(); owners } async fn owned_nfts(&self, owner: AccountOwner) -> BTreeMap<String, NftOutput> { let mut result = BTreeMap::new(); let owned_token_ids = self .non_fungible_token .owned_token_ids .get(&owner) .await .unwrap(); for token_id in owned_token_ids.into_iter().flatten() { let nft = self .non_fungible_token .nfts .get(&token_id) .await .unwrap() .unwrap(); let nft_output = NftOutput::new(nft); result.insert(nft_output.token_id.clone(), nft_output); } result } async fn prompt(&self, ctx: &Context<'_>, prompt: String) -> String { let runtime = ctx.data::<Arc<ServiceRuntime<GenNftService>>>().unwrap(); info!("prompt: {}", prompt); let response = runtime.http_request(http::Request::get("http://localhost:10001/model.bin")); let raw_weights = response.body; info!("got weights: {}B", raw_weights.len()); let response = runtime.http_request(http::Request::get("http://localhost:10001/tokenizer.json")); let tokenizer_bytes = response.body; let model_context = ModelContext { model: raw_weights, tokenizer: tokenizer_bytes, }; model_context.run_model(&prompt).unwrap() } } struct MutationRoot { runtime: Arc<ServiceRuntime<GenNftService>>, } #[Object] impl MutationRoot { async fn mint(&self, minter: AccountOwner, prompt: String) -> [u8; 0] { let operation = Operation::Mint { minter, prompt }; self.runtime.schedule_operation(&operation); [] } async fn transfer( &self, source_owner: AccountOwner, token_id: String, target_account: Account, ) -> [u8; 0] { let operation = Operation::Transfer { source_owner, token_id: TokenId { id: STANDARD_NO_PAD.decode(token_id).unwrap(), }, target_account, }; self.runtime.schedule_operation(&operation); [] } async fn claim( &self, source_account: Account, token_id: String, target_account: Account, ) -> [u8; 0] { let operation = Operation::Claim { source_account, token_id: TokenId { id: STANDARD_NO_PAD.decode(token_id).unwrap(), }, target_account, }; self.runtime.schedule_operation(&operation); [] } }
rust
Apache-2.0
69f159d2106f7fc70870ce70074c55850bf1303b
2026-01-04T15:33:08.660695Z
false
linera-io/linera-protocol
https://github.com/linera-io/linera-protocol/blob/69f159d2106f7fc70870ce70074c55850bf1303b/examples/gen-nft/src/model.rs
examples/gen-nft/src/model.rs
// Copyright (c) Zefchain Labs, Inc. // SPDX-License-Identifier: Apache-2.0 use std::io::{Cursor, Seek, SeekFrom}; use candle_core::{ quantized::{ggml_file, gguf_file}, Device, IndexOp, Tensor, }; use candle_transformers::{ generation::LogitsProcessor, models::{llama2_c, llama2_c::Llama, llama2_c_weights, quantized_llama::ModelWeights}, }; use log::info; use tokenizers::Tokenizer; use crate::token::TokenOutputStream; enum Model { Llama { model: Llama, cache: llama2_c::Cache, }, Qllama(ModelWeights), } impl Model { fn forward(&mut self, input: &Tensor, index_pos: usize) -> Result<Tensor, candle_core::Error> { match self { Model::Llama { model: llama, cache, } => llama.forward(input, index_pos, cache), Model::Qllama(model) => model.forward(input, index_pos), } } } pub struct ModelContext { pub(crate) model: Vec<u8>, pub(crate) tokenizer: Vec<u8>, } impl ModelContext { fn try_load_gguf(cursor: &mut Cursor<Vec<u8>>) -> Result<ModelWeights, candle_core::Error> { info!("trying to load model assuming gguf"); let model_contents = gguf_file::Content::read(cursor)?; let mut total_size_in_bytes = 0; for (_, tensor) in model_contents.tensor_infos.iter() { let elem_count = tensor.shape.elem_count(); total_size_in_bytes += elem_count * tensor.ggml_dtype.type_size() / tensor.ggml_dtype.block_size(); } info!( "loaded {:?} tensors ({}B) ", model_contents.tensor_infos.len(), total_size_in_bytes, ); ModelWeights::from_gguf(model_contents, cursor, &Device::Cpu) } fn try_load_ggml(cursor: &mut Cursor<Vec<u8>>) -> Result<ModelWeights, candle_core::Error> { info!("trying to load model assuming ggml"); let model_contents = ggml_file::Content::read(cursor, &Device::Cpu)?; let mut total_size_in_bytes = 0; for (_, tensor) in model_contents.tensors.iter() { let elem_count = tensor.shape().elem_count(); total_size_in_bytes += elem_count * tensor.dtype().type_size() / tensor.dtype().block_size(); } info!( "loaded {:?} tensors ({}B) ", model_contents.tensors.len(), total_size_in_bytes, ); ModelWeights::from_ggml(model_contents, 1) } fn try_load_non_quantized(cursor: &mut Cursor<Vec<u8>>) -> Result<Model, candle_core::Error> { let config = llama2_c::Config::from_reader(cursor)?; println!("{config:?}"); let weights = llama2_c_weights::TransformerWeights::from_reader(cursor, &config, &Device::Cpu)?; let vb = weights.var_builder(&config, &Device::Cpu)?; let cache = llama2_c::Cache::new(true, &config, vb.pp("rot"))?; let llama = Llama::load(vb, config.clone())?; Ok(Model::Llama { model: llama, cache, }) } fn load_model(&self, model_weights: Vec<u8>) -> Model { let mut cursor = Cursor::new(model_weights); if let Ok(model) = Self::try_load_gguf(&mut cursor) { return Model::Qllama(model); } cursor.seek(SeekFrom::Start(0)).expect("seeking to 0"); if let Ok(model) = Self::try_load_ggml(&mut cursor) { return Model::Qllama(model); } cursor.seek(SeekFrom::Start(0)).expect("seeking to 0"); if let Ok(model) = Self::try_load_non_quantized(&mut cursor) { return model; } // might need a 'model not supported variant' panic!("model failed to be loaded") } pub fn run_model(&self, prompt_string: &str) -> Result<String, candle_core::Error> { let raw_weights = &self.model; let tokenizer_bytes = &self.tokenizer; let mut output = String::new(); let mut model = self.load_model(raw_weights.clone()); let tokenizer = Tokenizer::from_bytes(tokenizer_bytes).expect("failed to create tokenizer"); let mut logits_processor = LogitsProcessor::new(299792458, None, None); let mut index_pos = 0; let mut tokens = tokenizer .encode(prompt_string, true) .unwrap() .get_ids() .to_vec(); let mut tokenizer = TokenOutputStream::new(tokenizer); for index in 0.. { let context_size = if index > 0 { 1 } else { tokens.len() }; let ctxt = &tokens[tokens.len().saturating_sub(context_size)..]; let input = Tensor::new(ctxt, &Device::Cpu)?.unsqueeze(0)?; if index_pos == 256 { return Ok(output .rsplit_once('.') .map_or_else(|| output.to_string(), |(before, _)| format!("{}.", before))); } let logits = model.forward(&input, index_pos)?; let logits = logits.i((0, logits.dim(1)? - 1))?; let start_at = tokens.len().saturating_sub(10); candle_transformers::utils::apply_repeat_penalty(&logits, 0.5, &tokens[start_at..])?; index_pos += ctxt.len(); let next_token = logits_processor.sample(&logits)?; tokens.push(next_token); if let Some(t) = tokenizer.next_token(next_token)? { output.push_str(&t); } } if let Some(rest) = tokenizer.decode_rest().unwrap() { output.push_str(&rest); output.insert_str(0, prompt_string); } Ok(output) } }
rust
Apache-2.0
69f159d2106f7fc70870ce70074c55850bf1303b
2026-01-04T15:33:08.660695Z
false
linera-io/linera-protocol
https://github.com/linera-io/linera-protocol/blob/69f159d2106f7fc70870ce70074c55850bf1303b/examples/gen-nft/src/token.rs
examples/gen-nft/src/token.rs
// Copyright (c) Zefchain Labs, Inc. // SPDX-License-Identifier: Apache-2.0 /// This is taken from https://github.com/huggingface/candle/blob/4fd00b890036ef67391a9cc03f896247d0a75711/candle-examples/src/token_output_stream.rs use candle_core::Result; /// This is a wrapper around a tokenizer to ensure that tokens can be returned to the user in a /// streaming way rather than having to wait for the full decoding. pub struct TokenOutputStream { tokenizer: tokenizers::Tokenizer, tokens: Vec<u32>, prev_index: usize, current_index: usize, } impl TokenOutputStream { pub fn new(tokenizer: tokenizers::Tokenizer) -> Self { Self { tokenizer, tokens: Vec::new(), prev_index: 0, current_index: 0, } } fn decode(&self, tokens: &[u32]) -> Result<String> { match self.tokenizer.decode(tokens, true) { Ok(str) => Ok(str), Err(err) => candle_core::bail!("cannot decode: {err}"), } } // https://github.com/huggingface/text-generation-inference/blob/5ba53d44a18983a4de32d122f4cb46f4a17d9ef6/server/text_generation_server/models/model.py#L68 pub fn next_token(&mut self, token: u32) -> Result<Option<String>> { let prev_text = if self.tokens.is_empty() { String::new() } else { let tokens = &self.tokens[self.prev_index..self.current_index]; self.decode(tokens)? }; self.tokens.push(token); let text = self.decode(&self.tokens[self.prev_index..])?; if text.len() > prev_text.len() && text.chars().last().unwrap().is_alphanumeric() { let text = text.split_at(prev_text.len()); self.prev_index = self.current_index; self.current_index = self.tokens.len(); Ok(Some(text.1.to_string())) } else { Ok(None) } } pub fn decode_rest(&self) -> Result<Option<String>> { let prev_text = if self.tokens.is_empty() { String::new() } else { let tokens = &self.tokens[self.prev_index..self.current_index]; self.decode(tokens)? }; let text = self.decode(&self.tokens[self.prev_index..])?; if text.len() > prev_text.len() { let text = text.split_at(prev_text.len()); Ok(Some(text.1.to_string())) } else { Ok(None) } } }
rust
Apache-2.0
69f159d2106f7fc70870ce70074c55850bf1303b
2026-01-04T15:33:08.660695Z
false
linera-io/linera-protocol
https://github.com/linera-io/linera-protocol/blob/69f159d2106f7fc70870ce70074c55850bf1303b/examples/hex-game/src/contract.rs
examples/hex-game/src/contract.rs
// Copyright (c) Zefchain Labs, Inc. // SPDX-License-Identifier: Apache-2.0 #![cfg_attr(target_arch = "wasm32", no_main)] mod state; use async_graphql::ComplexObject; use hex_game::{Board, Clock, HexAbi, HexOutcome, Operation, Timeouts}; use linera_sdk::{ linera_base_types::{ AccountOwner, Amount, ApplicationPermissions, ChainId, ChainOwnership, TimeoutConfig, WithContractAbi, }, views::{RootView, View}, Contract, ContractRuntime, }; use serde::{Deserialize, Serialize}; use state::{GameChain, HexState}; pub struct HexContract { state: HexState, runtime: ContractRuntime<Self>, } linera_sdk::contract!(HexContract); impl WithContractAbi for HexContract { type Abi = HexAbi; } impl Contract for HexContract { type Message = Message; type InstantiationArgument = Timeouts; type Parameters = (); type EventValue = (); async fn load(runtime: ContractRuntime<Self>) -> Self { let state = HexState::load(runtime.root_view_storage_context()) .await .expect("Failed to load state"); HexContract { state, runtime } } async fn instantiate(&mut self, arg: Timeouts) { log::trace!("Instantiating"); self.runtime.application_parameters(); // Verifies that these are empty. self.state.timeouts.set(arg); } async fn execute_operation(&mut self, operation: Operation) -> HexOutcome { log::trace!("Handling operation {:?}", operation); let outcome = match operation { Operation::MakeMove { x, y } => self.execute_make_move(x, y), Operation::ClaimVictory => self.execute_claim_victory(), Operation::Start { players, board_size, fee_budget, timeouts, } => { self.execute_start(players, board_size, fee_budget, timeouts) .await } }; self.handle_winner(outcome) } async fn execute_message(&mut self, message: Message) { log::trace!("Handling message {:?}", message); match message { Message::Start { players, board_size, timeouts, } => { let clock = Clock::new(self.runtime.system_time(), &timeouts); self.state.clock.set(clock); self.state.owners.set(Some(players)); self.state.board.set(Board::new(board_size)); } Message::End { winner, loser } => { let origin_chain_id = self.runtime.message_origin_chain_id().unwrap(); for owner in [&winner, &loser] { let chain_set = self .state .game_chains .get_mut_or_default(owner) .await .unwrap(); chain_set.retain(|game_chain| game_chain.chain_id != origin_chain_id); if chain_set.is_empty() { self.state.game_chains.remove(owner).unwrap(); } } } } } async fn store(mut self) { self.state.save().await.expect("Failed to save state"); } } impl HexContract { fn execute_make_move(&mut self, x: u16, y: u16) -> HexOutcome { assert!(self.runtime.chain_id() != self.main_chain_id()); let active = self.state.board.get().active_player(); let clock = self.state.clock.get_mut(); let block_time = self.runtime.system_time(); assert_eq!( self.runtime.authenticated_owner(), Some(self.state.owners.get().unwrap()[active.index()]), "Move must be signed by the player whose turn it is." ); self.runtime .assert_before(block_time.saturating_add(clock.block_delay)); clock.make_move(block_time, active); self.state.board.get_mut().make_move(x, y) } fn execute_claim_victory(&mut self) -> HexOutcome { assert!(self.runtime.chain_id() != self.main_chain_id()); let active = self.state.board.get().active_player(); let clock = self.state.clock.get_mut(); let block_time = self.runtime.system_time(); assert_eq!( self.runtime.authenticated_owner(), Some(self.state.owners.get().unwrap()[active.other().index()]), "Victory can only be claimed by the player whose turn it is not." ); assert!( clock.timed_out(block_time, active), "Player has not timed out yet." ); assert!( self.state.board.get().winner().is_none(), "The game has already ended." ); HexOutcome::Winner(active.other()) } async fn execute_start( &mut self, players: [AccountOwner; 2], board_size: u16, fee_budget: Amount, timeouts: Option<Timeouts>, ) -> HexOutcome { assert_eq!(self.runtime.chain_id(), self.main_chain_id()); let ownership = ChainOwnership::multiple( [(players[0], 100), (players[1], 100)], 100, TimeoutConfig::default(), ); let app_id = self.runtime.application_id(); let permissions = ApplicationPermissions::new_single(app_id.forget_abi()); let chain_id = self.runtime.open_chain(ownership, permissions, fee_budget); for owner in &players { self.state .game_chains .get_mut_or_default(owner) .await .unwrap() .insert(GameChain { chain_id }); } self.runtime.send_message( chain_id, Message::Start { players, board_size, timeouts: timeouts.unwrap_or_else(|| self.state.timeouts.get().clone()), }, ); HexOutcome::Ok } fn handle_winner(&mut self, outcome: HexOutcome) -> HexOutcome { let HexOutcome::Winner(player) = outcome else { return outcome; }; let winner = self.state.owners.get().unwrap()[player.index()]; let loser = self.state.owners.get().unwrap()[player.other().index()]; let chain_id = self.main_chain_id(); let message = Message::End { winner, loser }; self.runtime.send_message(chain_id, message); self.runtime.close_chain().unwrap(); outcome } fn main_chain_id(&mut self) -> ChainId { self.runtime.application_creator_chain_id() } } #[derive(Debug, Serialize, Deserialize)] pub enum Message { /// Initializes a game. Sent from the main chain to a temporary chain. Start { /// The players. players: [AccountOwner; 2], /// The side length of the board. A typical size is 11. board_size: u16, /// Settings that determine how much time the players have to think about their turns. timeouts: Timeouts, }, /// Reports the outcome of a game. Sent from a closed chain to the main chain. End { winner: AccountOwner, loser: AccountOwner, }, } /// This implementation is only nonempty in the service. #[ComplexObject] impl HexState {}
rust
Apache-2.0
69f159d2106f7fc70870ce70074c55850bf1303b
2026-01-04T15:33:08.660695Z
false
linera-io/linera-protocol
https://github.com/linera-io/linera-protocol/blob/69f159d2106f7fc70870ce70074c55850bf1303b/examples/hex-game/src/lib.rs
examples/hex-game/src/lib.rs
// Copyright (c) Zefchain Labs, Inc. // SPDX-License-Identifier: Apache-2.0 /*! ABI of the Hex game */ use std::iter; use async_graphql::{Enum, InputObject, Request, Response, SimpleObject}; use linera_sdk::{ graphql::GraphQLMutationRoot, linera_base_types::{AccountOwner, Amount, ContractAbi, ServiceAbi, TimeDelta, Timestamp}, }; use serde::{Deserialize, Serialize}; pub struct HexAbi; #[derive(Debug, Deserialize, Serialize, GraphQLMutationRoot)] pub enum Operation { /// Make a move, and place a stone onto cell `(x, y)`. MakeMove { x: u16, y: u16 }, /// Claim victory if the opponent has timed out. ClaimVictory, /// Start a game on a new temporary chain, with the given settings. Start { /// The public keys of player 1 and 2, respectively. players: [AccountOwner; 2], /// The side length of the board. A typical size is 11. board_size: u16, /// An amount transferred to the temporary chain to cover the fees. fee_budget: Amount, /// Settings that determine how much time the players have to think about their turns. /// If this is `None`, the defaults are used. timeouts: Option<Timeouts>, }, } impl ContractAbi for HexAbi { type Operation = Operation; type Response = HexOutcome; } impl ServiceAbi for HexAbi { type Query = Request; type QueryResponse = Response; } /// Settings that determine how much time the players have to think about their turns. #[derive(Clone, Debug, Deserialize, Serialize, SimpleObject, InputObject)] #[graphql(input_name = "TimeoutsInput")] #[serde(rename_all = "camelCase")] pub struct Timeouts { /// The initial time each player has to think about their turns. pub start_time: TimeDelta, /// The duration that is added to the clock after each turn. pub increment: TimeDelta, /// The maximum time that is allowed to pass between a block proposal and validation. /// This should be long enough to confirm a block, but short enough for the block timestamp /// to accurately reflect the current time. pub block_delay: TimeDelta, } impl Default for Timeouts { fn default() -> Timeouts { Timeouts { start_time: TimeDelta::from_secs(60), increment: TimeDelta::from_secs(30), block_delay: TimeDelta::from_secs(5), } } } /// A clock to track both players' time. #[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize, SimpleObject)] pub struct Clock { time_left: [TimeDelta; 2], increment: TimeDelta, current_turn_start: Timestamp, pub block_delay: TimeDelta, } impl Clock { /// Initializes the clock. pub fn new(block_time: Timestamp, timeouts: &Timeouts) -> Self { Self { time_left: [timeouts.start_time, timeouts.start_time], increment: timeouts.increment, current_turn_start: block_time, block_delay: timeouts.block_delay, } } /// Records a player making a move in the current block. pub fn make_move(&mut self, block_time: Timestamp, player: Player) { let duration = block_time.delta_since(self.current_turn_start); let i = player.index(); assert!(self.time_left[i] >= duration); self.time_left[i] = self.time_left[i] .saturating_sub(duration) .saturating_add(self.increment); self.current_turn_start = block_time; } /// Returns whether the given player has timed out. pub fn timed_out(&self, block_time: Timestamp, player: Player) -> bool { self.time_left[player.index()] < block_time.delta_since(self.current_turn_start) } } /// The outcome of a valid move. #[derive(Debug, PartialEq, Eq, Serialize, Deserialize)] pub enum HexOutcome { /// A player wins the game. Winner(Player), /// The game continues. Ok, } /// A player: `One` or `Two` /// /// It's player `One`'s turn whenever the number of stones on the board is even, so they make /// the first move. Otherwise it's `Two`'s turn. #[derive(Debug, Default, Copy, Clone, PartialEq, Eq, Serialize, Deserialize, Enum)] pub enum Player { #[default] /// Player one One, /// Player two Two, } impl Player { /// Returns the opponent of `self`. pub fn other(self) -> Self { match self { Player::One => Player::Two, Player::Two => Player::One, } } /// Returns `0` for player `One` and `1` for player `Two`. pub fn index(&self) -> usize { match self { Player::One => 0, Player::Two => 1, } } } /// The state of a cell on the board. #[derive(Default, Copy, Clone, PartialEq, Eq, Serialize, Deserialize, SimpleObject)] pub struct Cell { /// `None` if the cell is empty; otherwise the player who placed a stone here. stone: Option<Player>, /// This is `true` if the cell belongs to player `One` and is connected to the left edge /// of the board via other cells containing a stone placed by player `One`, or if it /// belongs to player `Two` and is connected to the top edge of the board via other cells /// containing stones placed by player `Two`. /// /// So the game ends if this is `true` for any cell at the right or bottom edge. connected: bool, } impl Cell { /// Returns whether this cell is connected to the top or left edge and belongs to the /// given player. fn is_connected(&self, player: Player) -> bool { self.connected && self.stone == Some(player) } } /// The state of a Hex game. #[derive(Clone, Default, Serialize, Deserialize, SimpleObject)] pub struct Board { /// The cells, row-by-row. /// /// Cell `(x, y)` has index `(x + y * size)`. cells: Vec<Cell>, /// The width and height of the board, in cells. size: u16, /// The player whose turn it is. If the game has ended, this player loses. active: Player, } impl Board { /// Creates a new board with the given size and player owners. pub fn new(size: u16) -> Self { let size_usize = usize::from(size); let cell_count = size_usize .checked_mul(size_usize) .expect("Board is too large."); let cells = vec![Cell::default(); cell_count]; Board { size, cells, active: Player::One, } } /// Updates the board: The active player places a stone on cell `(x, y)`. /// /// Panics if the move is invalid. pub fn make_move(&mut self, x: u16, y: u16) -> HexOutcome { assert!(self.winner().is_none(), "Game has ended."); assert!(x < self.size && y < self.size, "Invalid coordinates."); assert!(self.cell(x, y).stone.is_none(), "Cell is not empty."); self.place_stone(x, y); if let Some(winner) = self.winner() { return HexOutcome::Winner(winner); } HexOutcome::Ok } /// Places the active player's stone on the given cell, updates all cells' /// `connected` flags accordingly. The new cell _must_ be empty! fn place_stone(&mut self, x: u16, y: u16) { let player = self.active; self.cell_mut(x, y).stone = Some(player); self.active = player.other(); if !((x == 0 && player == Player::One) || (y == 0 && player == Player::Two) || self .neighbors(x, y) .any(|(nx, ny)| self.cell(nx, ny).is_connected(player))) { return; } let mut stack = vec![(x, y)]; while let Some((x, y)) = stack.pop() { self.cell_mut(x, y).connected = true; stack.extend(self.neighbors(x, y).filter(|(nx, ny)| { let cell = self.cell(*nx, *ny); !cell.connected && cell.stone == Some(player) })); } } /// Returns the winner, or `None` if the game is still in progress. pub fn winner(&self) -> Option<Player> { let s = self.size - 1; for i in 0..self.size { if self.cell(s, i).is_connected(Player::One) { return Some(Player::One); } if self.cell(i, s).is_connected(Player::Two) { return Some(Player::Two); } } None } /// Returns the `AccountOwner` controlling the active player. pub fn active_player(&self) -> Player { self.active } /// Returns the cell `(x, y)`. fn cell(&self, x: u16, y: u16) -> Cell { self.cells[x as usize + (y as usize) * (self.size as usize)] } /// Returns a mutable reference to cell `(x, y)`. fn cell_mut(&mut self, x: u16, y: u16) -> &mut Cell { &mut self.cells[x as usize + (y as usize) * (self.size as usize)] } /// Returns all neighbors of cell `(x, y)`, in the order: /// left, top left, right, bottom right, top right, bottom left fn neighbors(&self, x: u16, y: u16) -> impl Iterator<Item = (u16, u16)> { iter::empty() .chain((x > 0).then(|| (x - 1, y))) .chain((y > 0).then(|| (x, y - 1))) .chain((x + 1 < self.size).then(|| (x + 1, y))) .chain((y + 1 < self.size).then(|| (x, y + 1))) .chain((x + 1 < self.size && y > 0).then(|| (x + 1, y - 1))) .chain((y + 1 < self.size && x > 0).then(|| (x - 1, y + 1))) } } #[cfg(test)] mod tests { use super::*; #[test] fn test_simple_game() { let mut board = Board::new(3); // Make a few moves; no winner yet: // 0 2 2 // 2 1 0 // 1 0 1 assert_eq!(Player::One, board.active_player()); assert_eq!(HexOutcome::Ok, board.make_move(0, 2)); assert_eq!(Player::Two, board.active_player()); assert_eq!(HexOutcome::Ok, board.make_move(0, 1)); assert_eq!(HexOutcome::Ok, board.make_move(1, 1)); assert_eq!(HexOutcome::Ok, board.make_move(1, 0)); assert_eq!(HexOutcome::Ok, board.make_move(2, 2)); assert_eq!(HexOutcome::Ok, board.make_move(2, 0)); assert!(board.winner().is_none()); // Player 1 connects left to right and wins: assert_eq!(HexOutcome::Winner(Player::One), board.make_move(2, 1)); assert_eq!(Some(Player::One), board.winner()); } }
rust
Apache-2.0
69f159d2106f7fc70870ce70074c55850bf1303b
2026-01-04T15:33:08.660695Z
false
linera-io/linera-protocol
https://github.com/linera-io/linera-protocol/blob/69f159d2106f7fc70870ce70074c55850bf1303b/examples/hex-game/src/state.rs
examples/hex-game/src/state.rs
// Copyright (c) Zefchain Labs, Inc. // SPDX-License-Identifier: Apache-2.0 use std::collections::BTreeSet; use async_graphql::SimpleObject; use hex_game::{Board, Clock, Timeouts}; use linera_sdk::{ linera_base_types::{AccountOwner, ChainId}, views::{linera_views, MapView, RegisterView, RootView, ViewStorageContext}, }; use serde::{Deserialize, Serialize}; /// The IDs of a temporary chain for a single game of Hex. #[derive(Clone, Eq, PartialEq, Ord, PartialOrd, Serialize, Deserialize, SimpleObject)] pub struct GameChain { /// The ID of the temporary game chain itself. pub chain_id: ChainId, } /// The application state. #[derive(RootView, SimpleObject)] #[graphql(complex)] #[view(context = ViewStorageContext)] pub struct HexState { /// The `AccountOwner`s controlling players `One` and `Two`. pub owners: RegisterView<Option<[AccountOwner; 2]>>, /// The current game state. pub board: RegisterView<Board>, /// The game clock. pub clock: RegisterView<Clock>, /// The timeouts. pub timeouts: RegisterView<Timeouts>, /// Temporary chains for individual games, by player. pub game_chains: MapView<AccountOwner, BTreeSet<GameChain>>, }
rust
Apache-2.0
69f159d2106f7fc70870ce70074c55850bf1303b
2026-01-04T15:33:08.660695Z
false
linera-io/linera-protocol
https://github.com/linera-io/linera-protocol/blob/69f159d2106f7fc70870ce70074c55850bf1303b/examples/hex-game/src/service.rs
examples/hex-game/src/service.rs
// Copyright (c) Zefchain Labs, Inc. // SPDX-License-Identifier: Apache-2.0 #![cfg_attr(target_arch = "wasm32", no_main)] mod state; use std::sync::Arc; use async_graphql::{ComplexObject, Context, EmptySubscription, Request, Response, Schema}; use hex_game::{Operation, Player}; use linera_sdk::{ graphql::GraphQLMutationRoot as _, linera_base_types::WithServiceAbi, views::View, Service, ServiceRuntime, }; use self::state::HexState; #[derive(Clone)] pub struct HexService { runtime: Arc<ServiceRuntime<HexService>>, state: Arc<HexState>, } linera_sdk::service!(HexService); impl WithServiceAbi for HexService { type Abi = hex_game::HexAbi; } impl Service for HexService { type Parameters = (); async fn new(runtime: ServiceRuntime<Self>) -> Self { let state = HexState::load(runtime.root_view_storage_context()) .await .expect("Failed to load state"); HexService { runtime: Arc::new(runtime), state: Arc::new(state), } } async fn handle_query(&self, request: Request) -> Response { let schema = Schema::build( self.state.clone(), Operation::mutation_root(self.runtime.clone()), EmptySubscription, ) .data(self.runtime.clone()) .finish(); schema.execute(request).await } } #[ComplexObject] impl HexState { async fn winner(&self, ctx: &Context<'_>) -> Option<Player> { if let Some(winner) = self.board.get().winner() { return Some(winner); } let active = self.board.get().active_player(); let runtime = ctx.data::<Arc<ServiceRuntime<HexService>>>().unwrap(); let block_time = runtime.system_time(); if self.clock.get().timed_out(block_time, active) { return Some(active.other()); } None } } #[cfg(test)] mod tests { use async_graphql::{futures_util::FutureExt, Request}; use linera_sdk::{util::BlockingWait, views::View, Service, ServiceRuntime}; use serde_json::json; use super::*; #[test] fn query() { let runtime = ServiceRuntime::<HexService>::new(); let state = HexState::load(runtime.root_view_storage_context()) .blocking_wait() .expect("Failed to read from mock key value store"); let service = HexService { state: Arc::new(state), runtime: Arc::new(runtime), }; let response = service .handle_query(Request::new("{ clock { increment } }")) .now_or_never() .expect("Query should not await anything") .data .into_json() .expect("Response should be JSON"); assert_eq!(response, json!({"clock" : {"increment": 0}})) } }
rust
Apache-2.0
69f159d2106f7fc70870ce70074c55850bf1303b
2026-01-04T15:33:08.660695Z
false
linera-io/linera-protocol
https://github.com/linera-io/linera-protocol/blob/69f159d2106f7fc70870ce70074c55850bf1303b/examples/hex-game/tests/hex_game.rs
examples/hex-game/tests/hex_game.rs
// Copyright (c) Zefchain Labs, Inc. // SPDX-License-Identifier: Apache-2.0 //! Integration tests for the Hex application. #![cfg(not(target_arch = "wasm32"))] use hex_game::{HexAbi, Operation, Timeouts}; use linera_sdk::{ linera_base_types::{ AccountSecretKey, Amount, BlobType, ChainDescription, Secp256k1SecretKey, TimeDelta, }, test::{ActiveChain, QueryOutcome, TestValidator}, }; #[test_log::test(tokio::test)] async fn hex_game() { let key_pair1 = AccountSecretKey::generate(); let key_pair2 = AccountSecretKey::Secp256k1(Secp256k1SecretKey::generate()); let (validator, app_id, creation_chain) = TestValidator::with_current_application::<HexAbi, _, _>((), Timeouts::default()).await; let certificate = creation_chain .add_block(|block| { let operation = Operation::Start { board_size: 2, players: [key_pair1.public().into(), key_pair2.public().into()], fee_budget: Amount::ZERO, timeouts: None, }; block.with_operation(app_id, operation); }) .await; let block = certificate.inner().block(); let description = block .created_blobs() .into_iter() .filter_map(|(blob_id, blob)| { (blob_id.blob_type == BlobType::ChainDescription) .then(|| bcs::from_bytes::<ChainDescription>(blob.content().bytes()).unwrap()) }) .next() .unwrap(); let mut chain = ActiveChain::new(key_pair1.copy(), description, validator); chain .add_block(|block| { block.with_messages_from(&certificate); block.with_operation(app_id, Operation::MakeMove { x: 0, y: 0 }); }) .await; chain.set_key_pair(key_pair2.copy()); chain .add_block(|block| { block.with_operation(app_id, Operation::MakeMove { x: 0, y: 1 }); }) .await; chain.set_key_pair(key_pair1.copy()); chain .add_block(|block| { block.with_operation(app_id, Operation::MakeMove { x: 1, y: 1 }); }) .await; let QueryOutcome { response, .. } = chain.graphql_query(app_id, "query { winner }").await; assert!(response["winner"].is_null()); chain.set_key_pair(key_pair2.copy()); chain .add_block(|block| { block.with_operation(app_id, Operation::MakeMove { x: 1, y: 0 }); }) .await; let QueryOutcome { response, .. } = chain.graphql_query(app_id, "query { winner }").await; assert_eq!(Some("TWO"), response["winner"].as_str()); assert!(chain.is_closed().await); } #[tokio::test] async fn hex_game_clock() { let key_pair1 = AccountSecretKey::generate(); let key_pair2 = AccountSecretKey::Secp256k1(Secp256k1SecretKey::generate()); let timeouts = Timeouts { start_time: TimeDelta::from_secs(60), increment: TimeDelta::from_secs(30), block_delay: TimeDelta::from_secs(5), }; let (validator, app_id, creation_chain) = TestValidator::with_current_application::<HexAbi, _, _>((), Timeouts::default()).await; let time = validator.clock().current_time(); validator.clock().add( timeouts .block_delay .saturating_sub(TimeDelta::from_millis(1)), ); let certificate = creation_chain .add_block(|block| { let operation = Operation::Start { board_size: 2, players: [key_pair1.public().into(), key_pair2.public().into()], fee_budget: Amount::ZERO, timeouts: None, }; block.with_operation(app_id, operation).with_timestamp(time); }) .await; let block = certificate.inner().block(); let description = block .created_blobs() .into_iter() .filter_map(|(blob_id, blob)| { (blob_id.blob_type == BlobType::ChainDescription) .then(|| bcs::from_bytes::<ChainDescription>(blob.content().bytes()).unwrap()) }) .next() .unwrap(); let mut chain = ActiveChain::new(key_pair1.copy(), description, validator.clone()); chain .add_block(|block| { block .with_messages_from(&certificate) .with_operation(app_id, Operation::MakeMove { x: 0, y: 0 }) .with_timestamp(time); }) .await; validator.clock().add(TimeDelta::from_millis(1)); // Block timestamp is too far behind. chain.set_key_pair(key_pair2.copy()); assert!(chain .try_add_block(|block| { block .with_operation(app_id, Operation::MakeMove { x: 0, y: 1 }) .with_timestamp(time); }) .await .is_err()); validator.clock().add(timeouts.start_time); let time = validator.clock().current_time(); // Player 2 has timed out. assert!(chain .try_add_block(|block| { block .with_operation(app_id, Operation::MakeMove { x: 0, y: 1 }) .with_timestamp(time); }) .await .is_err()); chain.set_key_pair(key_pair1.copy()); chain .add_block(|block| { block .with_operation(app_id, Operation::ClaimVictory) .with_timestamp(time); }) .await; let QueryOutcome { response, .. } = chain.graphql_query(app_id, "query { winner }").await; assert_eq!(Some("ONE"), response["winner"].as_str()); }
rust
Apache-2.0
69f159d2106f7fc70870ce70074c55850bf1303b
2026-01-04T15:33:08.660695Z
false
linera-io/linera-protocol
https://github.com/linera-io/linera-protocol/blob/69f159d2106f7fc70870ce70074c55850bf1303b/examples/social/src/contract.rs
examples/social/src/contract.rs
// Copyright (c) Zefchain Labs, Inc. // SPDX-License-Identifier: Apache-2.0 #![cfg_attr(target_arch = "wasm32", no_main)] mod state; use linera_sdk::{ linera_base_types::{ChainId, StreamUpdate, WithContractAbi}, views::{RootView, View}, Contract, ContractRuntime, }; use serde::{Deserialize, Serialize}; use social::{Comment, Key, Message, Operation, OwnPost, Post, SocialAbi}; use state::SocialState; /// The stream name the application uses for events about posts, likes and comments. const STREAM_NAME: &[u8] = b"posts"; pub struct SocialContract { state: SocialState, runtime: ContractRuntime<Self>, } linera_sdk::contract!(SocialContract); impl WithContractAbi for SocialContract { type Abi = SocialAbi; } impl Contract for SocialContract { type Message = Message; type InstantiationArgument = (); type Parameters = (); type EventValue = Event; async fn load(runtime: ContractRuntime<Self>) -> Self { let state = SocialState::load(runtime.root_view_storage_context()) .await .expect("Failed to load state"); SocialContract { state, runtime } } async fn instantiate(&mut self, _argument: ()) { // Validate that the application parameters were configured correctly. self.runtime.application_parameters(); } async fn execute_operation(&mut self, operation: Operation) -> Self::Response { match operation { Operation::Subscribe { chain_id } => { let app_id = self.runtime.application_id().forget_abi(); self.runtime .subscribe_to_events(chain_id, app_id, STREAM_NAME.into()); } Operation::Unsubscribe { chain_id } => { let app_id = self.runtime.application_id().forget_abi(); self.runtime .unsubscribe_from_events(chain_id, app_id, STREAM_NAME.into()); } Operation::Post { text, image_url } => { self.execute_post_operation(text, image_url).await } Operation::Like { key } => self.execute_like_operation(key).await, Operation::Comment { key, comment } => { self.execute_comment_operation(key, comment).await } } } async fn execute_message(&mut self, message: Message) { match message { Message::Like { key } => self.runtime.emit(STREAM_NAME.into(), &Event::Like { key }), Message::Comment { key, comment } => self .runtime .emit(STREAM_NAME.into(), &Event::Comment { key, comment }), }; } async fn process_streams(&mut self, updates: Vec<StreamUpdate>) { for update in updates { assert_eq!(update.stream_id.stream_name, STREAM_NAME.into()); assert_eq!( update.stream_id.application_id, self.runtime.application_id().forget_abi().into() ); for index in update.new_indices() { let event = self .runtime .read_event(update.chain_id, STREAM_NAME.into(), index); match event { Event::Post { post, index } => { self.execute_post_event(update.chain_id, index, post); } Event::Like { key } => self.execute_like_event(key).await, Event::Comment { key, comment } => { self.execute_comment_event(key, update.chain_id, comment) .await; } } } } } async fn store(mut self) { self.state.save().await.expect("Failed to save state"); } } impl SocialContract { async fn execute_post_operation(&mut self, text: String, image_url: Option<String>) { let timestamp = self.runtime.system_time(); let post = OwnPost { timestamp, text, image_url, }; let index = self.state.own_posts.count().try_into().unwrap(); self.state.own_posts.push(post.clone()); self.runtime .emit(STREAM_NAME.into(), &Event::Post { post, index }); } async fn execute_like_operation(&mut self, key: Key) { let chain_id = key.author; if chain_id != self.runtime.chain_id() { self.runtime.send_message(chain_id, Message::Like { key }); } else { self.runtime.emit(STREAM_NAME.into(), &Event::Like { key }); } } async fn execute_comment_operation(&mut self, key: Key, comment: String) { let chain_id = key.author; if chain_id != self.runtime.chain_id() { self.runtime .send_message(chain_id, Message::Comment { key, comment }); } else { self.runtime .emit(STREAM_NAME.into(), &Event::Comment { key, comment }); } } fn execute_post_event(&mut self, chain_id: ChainId, index: u32, post: OwnPost) { let key = Key { timestamp: post.timestamp, author: chain_id, index, }; let new_post = Post { key: key.clone(), text: post.text, image_url: post.image_url, likes: 0, comments: vec![], }; self.state .received_posts .insert(&key, new_post) .expect("Failed to insert received post"); } async fn execute_like_event(&mut self, key: Key) { let mut post = self .state .received_posts .get(&key) .await .expect("Failed to retrieve post") .expect("Post not found"); post.likes += 1; self.state .received_posts .insert(&key, post) .expect("Failed to insert received post"); } async fn execute_comment_event(&mut self, key: Key, chain_id: ChainId, comment: String) { let mut post = self .state .received_posts .get(&key) .await .expect("Failed to retrieve post") .expect("Post not found"); let comment = Comment { chain_id, text: comment, }; post.comments.push(comment); self.state .received_posts .insert(&key, post) .expect("Failed to insert received post"); } } #[derive(Debug, PartialEq, Serialize, Deserialize)] pub enum Event { /// A new post was created Post { post: OwnPost, index: u32 }, /// A user liked a post Like { key: Key }, /// A user commented on a post Comment { key: Key, comment: String }, }
rust
Apache-2.0
69f159d2106f7fc70870ce70074c55850bf1303b
2026-01-04T15:33:08.660695Z
false
linera-io/linera-protocol
https://github.com/linera-io/linera-protocol/blob/69f159d2106f7fc70870ce70074c55850bf1303b/examples/social/src/lib.rs
examples/social/src/lib.rs
// Copyright (c) Zefchain Labs, Inc. // SPDX-License-Identifier: Apache-2.0 /*! ABI of the Social Media Example Application */ use async_graphql::{InputObject, Request, Response, SimpleObject}; use linera_sdk::{ graphql::GraphQLMutationRoot, linera_base_types::{ChainId, ContractAbi, ServiceAbi, Timestamp}, views::{CustomSerialize, ViewError}, }; use serde::{Deserialize, Serialize}; pub struct SocialAbi; impl ContractAbi for SocialAbi { type Operation = Operation; type Response = (); } impl ServiceAbi for SocialAbi { type Query = Request; type QueryResponse = Response; } /// An operation that can be executed by the application. #[derive(Debug, Serialize, Deserialize, GraphQLMutationRoot)] pub enum Operation { /// Request to be subscribed to another chain. Subscribe { chain_id: ChainId }, /// Request to be unsubscribed from another chain. Unsubscribe { chain_id: ChainId }, /// Send a new post to everyone who subscribed to us. Post { text: String, image_url: Option<String>, }, /// Like a post Like { key: Key }, /// Comment on a post Comment { key: Key, comment: String }, } #[derive(Debug, Serialize, Deserialize)] pub enum Message { /// Like a post, author of a post receives the message. Like { key: Key }, /// Comment on a post, author of a post receives the message. Comment { key: Key, comment: String }, } /// A post's text and timestamp, to use in contexts where author and index are known. #[derive(PartialEq, Debug, Clone, Serialize, Deserialize, SimpleObject)] pub struct OwnPost { /// The timestamp of the block in which the post operation was included. pub timestamp: Timestamp, /// The posted text. pub text: String, /// The posted Image_url(optional). pub image_url: Option<String>, } /// A post on the social app. #[derive(Clone, PartialEq, Debug, Serialize, Deserialize, SimpleObject)] pub struct Post { /// The key identifying the post, including the timestamp, author and index. pub key: Key, /// The post's text content. pub text: String, /// The post's image_url(optional). pub image_url: Option<String>, /// The total number of likes pub likes: u32, /// Comments with their ChainId pub comments: Vec<Comment>, } /// A comment on a post #[derive(Clone, PartialEq, Debug, Serialize, Deserialize, SimpleObject)] pub struct Comment { /// The comment text pub text: String, /// The ChainId of the commenter pub chain_id: ChainId, } /// A key by which a post is indexed. #[derive(Clone, PartialEq, Debug, Serialize, Deserialize, SimpleObject, InputObject)] #[graphql(input_name = "KeyInput")] pub struct Key { /// The timestamp of the block in which the post was included on the author's chain. pub timestamp: Timestamp, /// The owner of the chain on which the `Post` operation was included. pub author: ChainId, /// The number of posts by that author before this one. pub index: u32, } // Serialize keys so that the lexicographic order of the serialized keys corresponds to reverse // chronological order, then sorted by author, then by descending index. impl CustomSerialize for Key { fn to_custom_bytes(&self) -> Result<Vec<u8>, ViewError> { let data = ( (!self.timestamp.micros()).to_be_bytes(), &self.author, (!self.index).to_be_bytes(), ); Ok(bcs::to_bytes(&data)?) } fn from_custom_bytes(short_key: &[u8]) -> Result<Self, ViewError> { let (time_bytes, author, idx_bytes) = (bcs::from_bytes(short_key))?; Ok(Self { timestamp: Timestamp::from(!u64::from_be_bytes(time_bytes)), author, index: !u32::from_be_bytes(idx_bytes), }) } } #[cfg(test)] mod tests { use linera_sdk::{ linera_base_types::{ChainId, Timestamp}, views::CustomSerialize, }; use super::Key; #[test] fn test_key_custom_serialize() { let key = Key { timestamp: Timestamp::from(0x123456789ABCDEF), author: ChainId([0x12345, 0x6789A, 0xBCDEF, 0x0248A].into()), index: 0x76543210, }; let ser_key = key .to_custom_bytes() .expect("serialization of Key should succeed"); let deser_key = Key::from_custom_bytes(&ser_key).expect("deserialization of Key should succeed"); assert_eq!(key, deser_key); } }
rust
Apache-2.0
69f159d2106f7fc70870ce70074c55850bf1303b
2026-01-04T15:33:08.660695Z
false
linera-io/linera-protocol
https://github.com/linera-io/linera-protocol/blob/69f159d2106f7fc70870ce70074c55850bf1303b/examples/social/src/state.rs
examples/social/src/state.rs
// Copyright (c) Zefchain Labs, Inc. // SPDX-License-Identifier: Apache-2.0 use linera_sdk::views::{linera_views, CustomMapView, LogView, RootView, ViewStorageContext}; use social::{Key, OwnPost, Post}; /// The application state. #[derive(RootView, async_graphql::SimpleObject)] #[view(context = ViewStorageContext)] pub struct SocialState { /// Our posts. pub own_posts: LogView<OwnPost>, /// Posts we received from authors we subscribed to. pub received_posts: CustomMapView<Key, Post>, }
rust
Apache-2.0
69f159d2106f7fc70870ce70074c55850bf1303b
2026-01-04T15:33:08.660695Z
false
linera-io/linera-protocol
https://github.com/linera-io/linera-protocol/blob/69f159d2106f7fc70870ce70074c55850bf1303b/examples/social/src/service.rs
examples/social/src/service.rs
// Copyright (c) Zefchain Labs, Inc. // SPDX-License-Identifier: Apache-2.0 #![cfg_attr(target_arch = "wasm32", no_main)] mod state; use std::sync::Arc; use async_graphql::{EmptySubscription, Request, Response, Schema}; use linera_sdk::{ graphql::GraphQLMutationRoot as _, linera_base_types::WithServiceAbi, views::View, Service, ServiceRuntime, }; use social::Operation; use state::SocialState; pub struct SocialService { state: Arc<SocialState>, runtime: Arc<ServiceRuntime<Self>>, } linera_sdk::service!(SocialService); impl WithServiceAbi for SocialService { type Abi = social::SocialAbi; } impl Service for SocialService { type Parameters = (); async fn new(runtime: ServiceRuntime<Self>) -> Self { let state = SocialState::load(runtime.root_view_storage_context()) .await .expect("Failed to load state"); SocialService { state: Arc::new(state), runtime: Arc::new(runtime), } } async fn handle_query(&self, request: Request) -> Response { let schema = Schema::build( self.state.clone(), Operation::mutation_root(self.runtime.clone()), EmptySubscription, ) .finish(); schema.execute(request).await } }
rust
Apache-2.0
69f159d2106f7fc70870ce70074c55850bf1303b
2026-01-04T15:33:08.660695Z
false
linera-io/linera-protocol
https://github.com/linera-io/linera-protocol/blob/69f159d2106f7fc70870ce70074c55850bf1303b/examples/social/tests/cross_chain.rs
examples/social/tests/cross_chain.rs
// Copyright (c) Zefchain Labs, Inc. // SPDX-License-Identifier: Apache-2.0 //! Integration tests for the social network application. #![cfg(not(target_arch = "wasm32"))] use linera_sdk::test::{QueryOutcome, TestValidator}; use social::Operation; /// Test posting messages across microchains. /// /// Creates the application on chain2 indirectly from the subscription, then /// send a message to chain2 and see it received on chain1. #[tokio::test] async fn test_cross_chain_posting() { let (validator, module_id) = TestValidator::with_current_module::<social::SocialAbi, (), ()>().await; let mut chain1 = validator.new_chain().await; // Initialization is trivial for the social app let application_id = chain1.create_application(module_id, (), (), vec![]).await; let chain2 = validator.new_chain().await; // Subscribe chain1 to chain2 chain1 .add_block(|block| { block.with_operation( application_id, Operation::Subscribe { chain_id: chain2.id(), }, ); }) .await; // Post on chain2 chain2 .add_block(|block| { block.with_operation( application_id, Operation::Post { text: "Linera is the new Mastodon".to_string(), image_url: None, }, ); }) .await; // Now make chain1 handle the post. chain1.handle_new_events().await; // Querying the own posts let query = "query { ownPosts { entries(start: 0, end: 1) { timestamp, text } } }"; let QueryOutcome { response, .. } = chain2.graphql_query(application_id, query).await; let value = response["ownPosts"]["entries"][0]["text"].clone(); assert_eq!(value, "Linera is the new Mastodon".to_string()); // Now handling the received messages let query = "query { receivedPosts { keys { timestamp, author, index } } }"; let QueryOutcome { response, .. } = chain1.graphql_query(application_id, query).await; let author = response["receivedPosts"]["keys"][0]["author"].clone(); assert_eq!(author, chain2.id().to_string()); }
rust
Apache-2.0
69f159d2106f7fc70870ce70074c55850bf1303b
2026-01-04T15:33:08.660695Z
false
linera-io/linera-protocol
https://github.com/linera-io/linera-protocol/blob/69f159d2106f7fc70870ce70074c55850bf1303b/examples/ethereum-tracker/src/contract.rs
examples/ethereum-tracker/src/contract.rs
// Copyright (c) Zefchain Labs, Inc. // SPDX-License-Identifier: Apache-2.0 #![cfg_attr(target_arch = "wasm32", no_main)] mod state; use alloy_primitives::U256; use ethereum_tracker::{EthereumTrackerAbi, InstantiationArgument}; use linera_sdk::{ linera_base_types::WithContractAbi, views::{RootView, View}, Contract, ContractRuntime, }; use self::state::EthereumTrackerState; pub struct EthereumTrackerContract { state: EthereumTrackerState, runtime: ContractRuntime<Self>, } linera_sdk::contract!(EthereumTrackerContract); impl WithContractAbi for EthereumTrackerContract { type Abi = EthereumTrackerAbi; } impl Contract for EthereumTrackerContract { type Message = (); type InstantiationArgument = InstantiationArgument; type Parameters = (); type EventValue = (); async fn load(runtime: ContractRuntime<Self>) -> Self { let state = EthereumTrackerState::load(runtime.root_view_storage_context()) .await .expect("Failed to load state"); EthereumTrackerContract { state, runtime } } async fn instantiate(&mut self, argument: InstantiationArgument) { // Validate that the application parameters were configured correctly. self.runtime.application_parameters(); let InstantiationArgument { ethereum_endpoint, contract_address, start_block, } = argument; self.state.ethereum_endpoint.set(ethereum_endpoint); self.state.contract_address.set(contract_address); self.state.start_block.set(start_block); self.state .save() .await .expect("Failed to write updated storage"); self.read_initial().await; } async fn execute_operation(&mut self, operation: Self::Operation) -> Self::Response { // The only input is updating the database match operation { Self::Operation::Update { to_block } => self.update(to_block).await, } } async fn execute_message(&mut self, _message: ()) { panic!("Messages not supported"); } async fn store(mut self) { self.state.save().await.expect("Failed to save state"); } } impl EthereumTrackerContract { /// Reads the initial event emitted by the Ethereum contract, with the initial account and its /// balance. async fn read_initial(&mut self) { let request = async_graphql::Request::new("query { readInitialEvent }"); let application_id = self.runtime.application_id(); let response = self.runtime.query_service(application_id, &request); let async_graphql::Value::Object(data_object) = response.data else { panic!("Unexpected response from `readInitialEvent`: {response:#?}"); }; let async_graphql::Value::Object(ref initial_event) = data_object["readInitialEvent"] else { panic!("Unexpected response data from `readInitialEvent`: {data_object:#?}"); }; let async_graphql::Value::String(ref address) = initial_event["address"] else { panic!("Unexpected address in initial event: {initial_event:#?}"); }; let async_graphql::Value::String(ref balance_string) = initial_event["balance"] else { panic!("Unexpected balance in initial event: {initial_event:#?}"); }; let balance = balance_string .parse::<U256>() .expect("Balance could not be parsed"); self.state .accounts .insert(address, balance.into()) .expect("Failed to insert initial balance"); } /// Updates the accounts based on the transfer events emitted up to the `end_block`. async fn update(&mut self, end_block: u64) { let request = async_graphql::Request::new(format!( r#"query {{ readTransferEvents(endBlock: {end_block}) }}"# )); let application_id = self.runtime.application_id(); let response = self.runtime.query_service(application_id, &request); let async_graphql::Value::Object(data_object) = response.data else { panic!("Unexpected response from `readTransferEvents`: {response:#?}"); }; let async_graphql::Value::List(ref events) = data_object["readTransferEvents"] else { panic!("Unexpected response data from `readTransferEvents`: {data_object:#?}"); }; for event_value in events { let async_graphql::Value::Object(event) = event_value else { panic!("Unexpected event returned from `readTransferEvents`: {event_value:#?}"); }; let async_graphql::Value::String(ref source) = event["source"] else { panic!("Unexpected source address in transfer event: {event:#?}"); }; let async_graphql::Value::String(ref destination) = event["destination"] else { panic!("Unexpected destination address in transfer event: {event:#?}"); }; let async_graphql::Value::String(ref value_string) = event["value"] else { panic!("Unexpected balance in transfer event: {event:#?}"); }; let value = value_string .parse::<U256>() .expect("Balance could not be parsed"); { let source_balance = self .state .accounts .get_mut_or_default(source) .await .expect("Failed to read account balance for source address"); source_balance.value -= value; } { let destination_balance = self .state .accounts .get_mut_or_default(destination) .await .expect("Failed to read account balance for destination address"); destination_balance.value += value; } } self.state.start_block.set(end_block); } }
rust
Apache-2.0
69f159d2106f7fc70870ce70074c55850bf1303b
2026-01-04T15:33:08.660695Z
false
linera-io/linera-protocol
https://github.com/linera-io/linera-protocol/blob/69f159d2106f7fc70870ce70074c55850bf1303b/examples/ethereum-tracker/src/lib.rs
examples/ethereum-tracker/src/lib.rs
// Copyright (c) Zefchain Labs, Inc. // SPDX-License-Identifier: Apache-2.0 /*! A Linera application that reads events emitted by the `simple_token.sol` example from `linera-ethereum` and tracks the balances. This shows how Wasm contracts on Linera can consume information generated by EVM contracts on Ethereum. */ use alloy_primitives::U256; use async_graphql::{scalar, Request, Response, SimpleObject}; use linera_sdk::{ graphql::GraphQLMutationRoot, linera_base_types::{ContractAbi, ServiceAbi}, }; use serde::{Deserialize, Serialize}; pub struct EthereumTrackerAbi; impl ContractAbi for EthereumTrackerAbi { type Operation = Operation; type Response = (); } impl ServiceAbi for EthereumTrackerAbi { type Query = Request; type QueryResponse = Response; } /// The possible operation for the node #[derive(Debug, Deserialize, Serialize, GraphQLMutationRoot)] pub enum Operation { /// Update the database by querying an Ethereum node /// up to an exclusive block number Update { to_block: u64 }, } /// The instantiation argument used for the contract. #[derive(Clone, Debug, Default, Deserialize, Serialize, SimpleObject)] pub struct InstantiationArgument { /// The Ethereum endpoint being used pub ethereum_endpoint: String, /// The address of the contract pub contract_address: String, /// The block height at which the EVM contract was created pub start_block: u64, } #[derive(Clone, Default, Deserialize, Serialize)] pub struct U256Cont { pub value: U256, } scalar!(U256Cont); impl From<U256> for U256Cont { fn from(value: U256) -> Self { U256Cont { value } } }
rust
Apache-2.0
69f159d2106f7fc70870ce70074c55850bf1303b
2026-01-04T15:33:08.660695Z
false
linera-io/linera-protocol
https://github.com/linera-io/linera-protocol/blob/69f159d2106f7fc70870ce70074c55850bf1303b/examples/ethereum-tracker/src/state.rs
examples/ethereum-tracker/src/state.rs
// Copyright (c) Zefchain Labs, Inc. // SPDX-License-Identifier: Apache-2.0 use ethereum_tracker::U256Cont; use linera_sdk::views::{linera_views, MapView, RegisterView, RootView, ViewStorageContext}; /// The application state. #[derive(RootView, async_graphql::SimpleObject)] #[view(context = ViewStorageContext)] pub struct EthereumTrackerState { pub ethereum_endpoint: RegisterView<String>, pub contract_address: RegisterView<String>, pub start_block: RegisterView<u64>, pub accounts: MapView<String, U256Cont>, }
rust
Apache-2.0
69f159d2106f7fc70870ce70074c55850bf1303b
2026-01-04T15:33:08.660695Z
false
linera-io/linera-protocol
https://github.com/linera-io/linera-protocol/blob/69f159d2106f7fc70870ce70074c55850bf1303b/examples/ethereum-tracker/src/service.rs
examples/ethereum-tracker/src/service.rs
// Copyright (c) Zefchain Labs, Inc. // SPDX-License-Identifier: Apache-2.0 #![cfg_attr(target_arch = "wasm32", no_main)] mod state; use std::sync::Arc; use alloy_primitives::U256; use async_graphql::{EmptySubscription, Request, Response, Schema}; use ethereum_tracker::Operation; use linera_sdk::{ ethereum::{EthereumDataType, EthereumEvent, EthereumQueries, ServiceEthereumClient}, graphql::GraphQLMutationRoot as _, linera_base_types::WithServiceAbi, views::View, Service, ServiceRuntime, }; use serde::{Deserialize, Serialize}; use self::state::EthereumTrackerState; #[derive(Clone, async_graphql::SimpleObject)] pub struct EthereumTrackerService { #[graphql(flatten)] state: Arc<EthereumTrackerState>, #[graphql(skip)] runtime: Arc<ServiceRuntime<Self>>, } linera_sdk::service!(EthereumTrackerService); impl WithServiceAbi for EthereumTrackerService { type Abi = ethereum_tracker::EthereumTrackerAbi; } impl Service for EthereumTrackerService { type Parameters = (); async fn new(runtime: ServiceRuntime<Self>) -> Self { let state = EthereumTrackerState::load(runtime.root_view_storage_context()) .await .expect("Failed to load state"); EthereumTrackerService { state: Arc::new(state), runtime: Arc::new(runtime), } } async fn handle_query(&self, request: Request) -> Response { let schema = Schema::build( Query { service: self.clone(), }, Operation::mutation_root(self.runtime.clone()), EmptySubscription, ) .finish(); schema.execute(request).await } } /// The service handler for GraphQL queries. #[derive(async_graphql::SimpleObject)] #[graphql(complex)] pub struct Query { #[graphql(flatten)] service: EthereumTrackerService, } #[async_graphql::ComplexObject] impl Query { /// Reads the initial Ethereum event emitted by the monitored contract. async fn read_initial_event(&self) -> InitialEvent { let start_block = *self.service.state.start_block.get(); let mut events = self .read_events("Initial(address,uint256)", start_block, start_block + 1) .await; assert_eq!(events.len(), 1); let mut event_values = events.pop().unwrap().values.into_iter(); let address_value = event_values.next().expect("Missing initial address value"); let balance_value = event_values.next().expect("Missing initial balance value"); let EthereumDataType::Address(address) = address_value else { panic!("wrong type for the first entry"); }; let EthereumDataType::Uint256(balance) = balance_value else { panic!("wrong type for the second entry"); }; InitialEvent { address, balance } } /// Reads the transfer events emitted by the monitored Ethereum contract. async fn read_transfer_events(&self, end_block: u64) -> Vec<TransferEvent> { let start_block = *self.service.state.start_block.get(); let events = self .read_events( "Transfer(address indexed,address indexed,uint256)", start_block, end_block, ) .await; events .into_iter() .map(|event| { let mut event_values = event.values.into_iter(); let source_value = event_values .next() .expect("Missing source address in response"); let destination_value = event_values .next() .expect("Missing destination address in response"); let amount_value = event_values.next().expect("Missing amount in response"); let EthereumDataType::Address(source) = source_value else { panic!("Wrong type for the source address"); }; let EthereumDataType::Address(destination) = destination_value else { panic!("Wrong type for the destination address"); }; let EthereumDataType::Uint256(value) = amount_value else { panic!("Wrong type for the amount"); }; TransferEvent { source, value, destination, } }) .collect() } } impl Query { /// Reads events of type `event_name` from the monitored contract emitted during the requested /// block height range. async fn read_events( &self, event_name: &str, start_block: u64, end_block: u64, ) -> Vec<EthereumEvent> { let url = self.service.state.ethereum_endpoint.get().clone(); let contract_address = self.service.state.contract_address.get().clone(); let ethereum_client = ServiceEthereumClient { url }; ethereum_client .read_events(&contract_address, event_name, start_block, end_block) .await .unwrap_or_else(|error| { panic!( "Failed to read Ethereum events for {contract_address} \ from block {start_block} to block {end_block}: {error}" ) }) } } /// The initial event emitted by the contract. #[derive(Clone, Default, Deserialize, Serialize)] pub struct InitialEvent { address: String, balance: U256, } async_graphql::scalar!(InitialEvent); /// The transfer events emitted by the contract. #[derive(Clone, Default, Deserialize, Serialize)] pub struct TransferEvent { source: String, value: U256, destination: String, } async_graphql::scalar!(TransferEvent);
rust
Apache-2.0
69f159d2106f7fc70870ce70074c55850bf1303b
2026-01-04T15:33:08.660695Z
false
linera-io/linera-protocol
https://github.com/linera-io/linera-protocol/blob/69f159d2106f7fc70870ce70074c55850bf1303b/examples/llm/src/random.rs
examples/llm/src/random.rs
// Copyright (c) Zefchain Labs, Inc. // SPDX-License-Identifier: Apache-2.0 use std::sync::{Mutex, OnceLock}; use rand::{rngs::StdRng, Rng, SeedableRng}; static RNG: OnceLock<Mutex<StdRng>> = OnceLock::new(); fn custom_getrandom(buf: &mut [u8]) -> Result<(), getrandom::Error> { let seed = [0u8; 32]; RNG.get_or_init(|| Mutex::new(StdRng::from_seed(seed))) .lock() .expect("failed to get RNG lock") .fill(buf); Ok(()) } getrandom::register_custom_getrandom!(custom_getrandom);
rust
Apache-2.0
69f159d2106f7fc70870ce70074c55850bf1303b
2026-01-04T15:33:08.660695Z
false
linera-io/linera-protocol
https://github.com/linera-io/linera-protocol/blob/69f159d2106f7fc70870ce70074c55850bf1303b/examples/llm/src/contract.rs
examples/llm/src/contract.rs
// Copyright (c) Zefchain Labs, Inc. // SPDX-License-Identifier: Apache-2.0 #![cfg_attr(target_arch = "wasm32", no_main)] use linera_sdk::{linera_base_types::WithContractAbi, Contract, ContractRuntime}; pub struct LlmContract; linera_sdk::contract!(LlmContract); impl WithContractAbi for LlmContract { type Abi = llm::LlmAbi; } impl Contract for LlmContract { type Message = (); type InstantiationArgument = (); type Parameters = (); type EventValue = (); async fn load(_runtime: ContractRuntime<Self>) -> Self { LlmContract } async fn instantiate(&mut self, _value: ()) {} async fn execute_operation(&mut self, _operation: ()) -> Self::Response {} async fn execute_message(&mut self, _message: ()) { panic!("Llm application doesn't support any cross-chain messages"); } async fn store(self) {} }
rust
Apache-2.0
69f159d2106f7fc70870ce70074c55850bf1303b
2026-01-04T15:33:08.660695Z
false
linera-io/linera-protocol
https://github.com/linera-io/linera-protocol/blob/69f159d2106f7fc70870ce70074c55850bf1303b/examples/llm/src/lib.rs
examples/llm/src/lib.rs
// Copyright (c) Zefchain Labs, Inc. // SPDX-License-Identifier: Apache-2.0 /*! ABI of the LLM Example Application */ use async_graphql::{Request, Response}; use linera_sdk::linera_base_types::{ContractAbi, ServiceAbi}; pub struct LlmAbi; impl ContractAbi for LlmAbi { type Operation = (); type Response = (); } impl ServiceAbi for LlmAbi { type Query = Request; type QueryResponse = Response; }
rust
Apache-2.0
69f159d2106f7fc70870ce70074c55850bf1303b
2026-01-04T15:33:08.660695Z
false
linera-io/linera-protocol
https://github.com/linera-io/linera-protocol/blob/69f159d2106f7fc70870ce70074c55850bf1303b/examples/llm/src/service.rs
examples/llm/src/service.rs
// Copyright (c) Zefchain Labs, Inc. // SPDX-License-Identifier: Apache-2.0 #![cfg_attr(target_arch = "wasm32", no_main)] mod random; mod token; use std::{ io::{Cursor, Seek, SeekFrom}, sync::Arc, }; use async_graphql::{Context, EmptyMutation, EmptySubscription, Object, Request, Response, Schema}; use candle_core::{ quantized::{ggml_file, gguf_file}, Device, IndexOp, Tensor, }; use candle_transformers::{ generation::LogitsProcessor, models::{llama2_c, llama2_c::Llama, llama2_c_weights, quantized_llama::ModelWeights}, }; use linera_sdk::{http, linera_base_types::WithServiceAbi, Service, ServiceRuntime}; use log::{debug, info}; use sha3::{Digest as _, Sha3_256}; use tokenizers::Tokenizer; use crate::token::TokenOutputStream; /// The SHA3-256 hash of the model weights to use. const WEIGHTS_HASH: &[u8] = &[ 0x23, 0x42, 0x71, 0xe1, 0xf8, 0x3b, 0x6e, 0xec, 0xf1, 0x9b, 0xa4, 0xb7, 0xf4, 0x52, 0x49, 0xe7, 0xd9, 0xc6, 0x86, 0x57, 0xbc, 0xa0, 0x2d, 0xa3, 0x9b, 0xdb, 0xb1, 0x49, 0xcd, 0x53, 0x10, 0x01, ]; /// The SHA3-256 hash of the tokenizer to use. const TOKENIZER_HASH: &[u8] = &[ 0x4a, 0x33, 0x4c, 0x71, 0x85, 0x96, 0xca, 0x0b, 0x0a, 0x03, 0x11, 0x56, 0x0a, 0x50, 0x25, 0xfd, 0xfc, 0x36, 0x8f, 0x33, 0x64, 0x17, 0x2b, 0x74, 0x01, 0xbb, 0x89, 0xbf, 0x30, 0x99, 0x20, 0x0b, ]; pub struct LlmService { model_context: Arc<ModelContext>, } linera_sdk::service!(LlmService); impl WithServiceAbi for LlmService { type Abi = llm::LlmAbi; } struct QueryRoot {} #[Object] impl QueryRoot { async fn prompt(&self, ctx: &Context<'_>, prompt: String) -> String { let model_context = ctx.data::<Arc<ModelContext>>().unwrap(); model_context.run_model(&prompt).unwrap() } } enum Model { Llama { model: Llama, cache: llama2_c::Cache, }, Qllama(ModelWeights), } impl Model { fn forward(&mut self, input: &Tensor, index_pos: usize) -> Result<Tensor, candle_core::Error> { match self { Model::Llama { model: llama, cache, } => llama.forward(input, index_pos, cache), Model::Qllama(model) => model.forward(input, index_pos), } } } struct ModelContext { model: Vec<u8>, tokenizer: Vec<u8>, } impl Service for LlmService { type Parameters = (); async fn new(runtime: ServiceRuntime<Self>) -> Self { info!("Downloading model"); let response = runtime.http_request(http::Request::get( "https://huggingface.co/karpathy/tinyllamas/resolve/main/stories42M.bin", )); let raw_weights = response.body; assert_eq!( Sha3_256::digest(&raw_weights).as_slice(), WEIGHTS_HASH, "Incorrect model was fetched" ); info!("Downloaded model weights: {} bytes", raw_weights.len()); info!("Downloading tokenizer"); let response = runtime.http_request(http::Request::get( "https://huggingface.co/spaces/lmz/candle-llama2/resolve/main/tokenizer.json", )); let tokenizer_bytes = response.body; assert_eq!( Sha3_256::digest(&tokenizer_bytes).as_slice(), TOKENIZER_HASH, "Incorrect tokenizer was fetched" ); info!("Downloaded tokenizer: {} bytes", tokenizer_bytes.len()); let model_context = Arc::new(ModelContext { model: raw_weights, tokenizer: tokenizer_bytes, }); LlmService { model_context } } async fn handle_query(&self, request: Request) -> Response { let query_string = &request.query; debug!("query: {}", query_string); let schema = Schema::build(QueryRoot {}, EmptyMutation, EmptySubscription) .data(self.model_context.clone()) .finish(); schema.execute(request).await } } impl ModelContext { fn try_load_gguf(cursor: &mut Cursor<Vec<u8>>) -> Result<ModelWeights, candle_core::Error> { debug!("trying to load model assuming gguf"); let model_contents = gguf_file::Content::read(cursor)?; let mut total_size_in_bytes = 0; for (_, tensor) in model_contents.tensor_infos.iter() { let elem_count = tensor.shape.elem_count(); total_size_in_bytes += elem_count * tensor.ggml_dtype.type_size() / tensor.ggml_dtype.block_size(); } debug!( "loaded {:?} tensors ({}B) ", model_contents.tensor_infos.len(), total_size_in_bytes, ); ModelWeights::from_gguf(model_contents, cursor, &Device::Cpu) } fn try_load_ggml(cursor: &mut Cursor<Vec<u8>>) -> Result<ModelWeights, candle_core::Error> { debug!("trying to load model assuming ggml"); let model_contents = ggml_file::Content::read(cursor, &Device::Cpu)?; let mut total_size_in_bytes = 0; for (_, tensor) in model_contents.tensors.iter() { let elem_count = tensor.shape().elem_count(); total_size_in_bytes += elem_count * tensor.dtype().type_size() / tensor.dtype().block_size(); } debug!( "loaded {:?} tensors ({}B) ", model_contents.tensors.len(), total_size_in_bytes, ); ModelWeights::from_ggml(model_contents, 1) } fn try_load_non_quantized(cursor: &mut Cursor<Vec<u8>>) -> Result<Model, candle_core::Error> { let config = llama2_c::Config::from_reader(cursor)?; println!("{config:?}"); let weights = llama2_c_weights::TransformerWeights::from_reader(cursor, &config, &Device::Cpu)?; let vb = weights.var_builder(&config, &Device::Cpu)?; let cache = llama2_c::Cache::new(true, &config, vb.pp("rot"))?; let llama = Llama::load(vb, config.clone())?; Ok(Model::Llama { model: llama, cache, }) } fn load_model(&self, model_weights: Vec<u8>) -> Model { let mut cursor = Cursor::new(model_weights); if let Ok(model) = Self::try_load_gguf(&mut cursor) { return Model::Qllama(model); } cursor.seek(SeekFrom::Start(0)).expect("seeking to 0"); if let Ok(model) = Self::try_load_ggml(&mut cursor) { return Model::Qllama(model); } cursor.seek(SeekFrom::Start(0)).expect("seeking to 0"); if let Ok(model) = Self::try_load_non_quantized(&mut cursor) { return model; } // might need a 'model not supported variant' panic!("model failed to be loaded") } fn run_model(&self, prompt_string: &str) -> Result<String, candle_core::Error> { let raw_weights = &self.model; let tokenizer_bytes = &self.tokenizer; let mut output = String::new(); let mut model = self.load_model(raw_weights.clone()); let tokenizer = Tokenizer::from_bytes(tokenizer_bytes).expect("failed to create tokenizer"); let mut logits_processor = LogitsProcessor::new(299792458, None, None); let mut index_pos = 0; let mut tokens = tokenizer .encode(prompt_string, true) .unwrap() .get_ids() .to_vec(); let mut tokenizer = TokenOutputStream::new(tokenizer); for index in 0.. { let context_size = if index > 0 { 1 } else { tokens.len() }; let ctxt = &tokens[tokens.len().saturating_sub(context_size)..]; let input = Tensor::new(ctxt, &Device::Cpu)?.unsqueeze(0)?; if index_pos == 256 { return Ok(output .rsplit_once('.') .map_or_else(|| output.to_string(), |(before, _)| format!("{}.", before))); } let logits = model.forward(&input, index_pos)?; let logits = logits.i((0, logits.dim(1)? - 1))?; let start_at = tokens.len().saturating_sub(10); candle_transformers::utils::apply_repeat_penalty(&logits, 0.5, &tokens[start_at..])?; index_pos += ctxt.len(); let next_token = logits_processor.sample(&logits)?; tokens.push(next_token); if let Some(t) = tokenizer.next_token(next_token)? { output.push_str(&t); } } if let Some(rest) = tokenizer.decode_rest().unwrap() { output.push_str(&rest); output.insert_str(0, prompt_string); } Ok(output) } }
rust
Apache-2.0
69f159d2106f7fc70870ce70074c55850bf1303b
2026-01-04T15:33:08.660695Z
false
linera-io/linera-protocol
https://github.com/linera-io/linera-protocol/blob/69f159d2106f7fc70870ce70074c55850bf1303b/examples/llm/src/token.rs
examples/llm/src/token.rs
// Copyright (c) Zefchain Labs, Inc. // SPDX-License-Identifier: Apache-2.0 /// This is taken from https://github.com/huggingface/candle/blob/4fd00b890036ef67391a9cc03f896247d0a75711/candle-examples/src/token_output_stream.rs use candle_core::Result; /// This is a wrapper around a tokenizer to ensure that tokens can be returned to the user in a /// streaming way rather than having to wait for the full decoding. pub struct TokenOutputStream { tokenizer: tokenizers::Tokenizer, tokens: Vec<u32>, prev_index: usize, current_index: usize, } impl TokenOutputStream { pub fn new(tokenizer: tokenizers::Tokenizer) -> Self { Self { tokenizer, tokens: Vec::new(), prev_index: 0, current_index: 0, } } fn decode(&self, tokens: &[u32]) -> Result<String> { match self.tokenizer.decode(tokens, true) { Ok(str) => Ok(str), Err(err) => candle_core::bail!("cannot decode: {err}"), } } // https://github.com/huggingface/text-generation-inference/blob/5ba53d44a18983a4de32d122f4cb46f4a17d9ef6/server/text_generation_server/models/model.py#L68 pub fn next_token(&mut self, token: u32) -> Result<Option<String>> { let prev_text = if self.tokens.is_empty() { String::new() } else { let tokens = &self.tokens[self.prev_index..self.current_index]; self.decode(tokens)? }; self.tokens.push(token); let text = self.decode(&self.tokens[self.prev_index..])?; if text.len() > prev_text.len() && text.chars().last().unwrap().is_alphanumeric() { let text = text.split_at(prev_text.len()); self.prev_index = self.current_index; self.current_index = self.tokens.len(); Ok(Some(text.1.to_string())) } else { Ok(None) } } pub fn decode_rest(&self) -> Result<Option<String>> { let prev_text = if self.tokens.is_empty() { String::new() } else { let tokens = &self.tokens[self.prev_index..self.current_index]; self.decode(tokens)? }; let text = self.decode(&self.tokens[self.prev_index..])?; if text.len() > prev_text.len() { let text = text.split_at(prev_text.len()); Ok(Some(text.1.to_string())) } else { Ok(None) } } }
rust
Apache-2.0
69f159d2106f7fc70870ce70074c55850bf1303b
2026-01-04T15:33:08.660695Z
false
linera-io/linera-protocol
https://github.com/linera-io/linera-protocol/blob/69f159d2106f7fc70870ce70074c55850bf1303b/examples/counter/src/contract.rs
examples/counter/src/contract.rs
// Copyright (c) Zefchain Labs, Inc. // SPDX-License-Identifier: Apache-2.0 #![cfg_attr(target_arch = "wasm32", no_main)] mod state; use counter::{CounterAbi, CounterOperation}; use linera_sdk::{ linera_base_types::WithContractAbi, views::{RootView, View}, Contract, ContractRuntime, }; use self::state::CounterState; pub struct CounterContract { state: CounterState, runtime: ContractRuntime<Self>, } linera_sdk::contract!(CounterContract); impl WithContractAbi for CounterContract { type Abi = CounterAbi; } impl Contract for CounterContract { type Message = (); type InstantiationArgument = u64; type Parameters = (); type EventValue = (); async fn load(runtime: ContractRuntime<Self>) -> Self { let state = CounterState::load(runtime.root_view_storage_context()) .await .expect("Failed to load state"); CounterContract { state, runtime } } async fn instantiate(&mut self, value: u64) { // Validate that the application parameters were configured correctly. self.runtime.application_parameters(); self.state.value.set(value); } async fn execute_operation(&mut self, operation: CounterOperation) -> u64 { let CounterOperation::Increment { value } = operation; let new_value = self.state.value.get() + value; self.state.value.set(new_value); new_value } async fn execute_message(&mut self, _message: ()) { panic!("Counter application doesn't support any cross-chain messages"); } async fn store(mut self) { self.state.save().await.expect("Failed to save state"); } } #[cfg(test)] mod tests { use counter::CounterOperation; use futures::FutureExt as _; use linera_sdk::{util::BlockingWait, views::View, Contract, ContractRuntime}; use super::{CounterContract, CounterState}; #[test] fn operation() { let initial_value = 72_u64; let mut counter = create_and_instantiate_counter(initial_value); let increment = 42_308_u64; let operation = CounterOperation::Increment { value: increment }; let response = counter .execute_operation(operation) .now_or_never() .expect("Execution of counter operation should not await anything"); let expected_value = initial_value + increment; assert_eq!(response, expected_value); assert_eq!(*counter.state.value.get(), initial_value + increment); } #[test] #[should_panic(expected = "Counter application doesn't support any cross-chain messages")] fn message() { let initial_value = 72_u64; let mut counter = create_and_instantiate_counter(initial_value); counter .execute_message(()) .now_or_never() .expect("Execution of counter operation should not await anything"); } #[test] fn cross_application_call() { let initial_value = 2_845_u64; let mut counter = create_and_instantiate_counter(initial_value); let increment = 8_u64; let operation = CounterOperation::Increment { value: increment }; let response = counter .execute_operation(operation) .now_or_never() .expect("Execution of counter operation should not await anything"); let expected_value = initial_value + increment; assert_eq!(response, expected_value); assert_eq!(*counter.state.value.get(), expected_value); } fn create_and_instantiate_counter(initial_value: u64) -> CounterContract { let runtime = ContractRuntime::new().with_application_parameters(()); let mut contract = CounterContract { state: CounterState::load(runtime.root_view_storage_context()) .blocking_wait() .expect("Failed to read from mock key value store"), runtime, }; contract .instantiate(initial_value) .now_or_never() .expect("Initialization of counter state should not await anything"); assert_eq!(*contract.state.value.get(), initial_value); contract } }
rust
Apache-2.0
69f159d2106f7fc70870ce70074c55850bf1303b
2026-01-04T15:33:08.660695Z
false
linera-io/linera-protocol
https://github.com/linera-io/linera-protocol/blob/69f159d2106f7fc70870ce70074c55850bf1303b/examples/counter/src/lib.rs
examples/counter/src/lib.rs
// Copyright (c) Zefchain Labs, Inc. // SPDX-License-Identifier: Apache-2.0 /*! ABI of the Counter Example Application */ use async_graphql::{Request, Response}; use linera_sdk::linera_base_types::{ContractAbi, ServiceAbi}; use serde::{Deserialize, Serialize}; pub struct CounterAbi; #[derive(Debug, Deserialize, Serialize)] pub enum CounterOperation { /// Increment the counter by the given value Increment { value: u64 }, } impl ContractAbi for CounterAbi { type Operation = CounterOperation; type Response = u64; } impl ServiceAbi for CounterAbi { type Query = Request; type QueryResponse = Response; }
rust
Apache-2.0
69f159d2106f7fc70870ce70074c55850bf1303b
2026-01-04T15:33:08.660695Z
false
linera-io/linera-protocol
https://github.com/linera-io/linera-protocol/blob/69f159d2106f7fc70870ce70074c55850bf1303b/examples/counter/src/state.rs
examples/counter/src/state.rs
// Copyright (c) Zefchain Labs, Inc. // SPDX-License-Identifier: Apache-2.0 use linera_sdk::views::{linera_views, RegisterView, RootView, ViewStorageContext}; /// The application state. #[derive(RootView, async_graphql::SimpleObject)] #[view(context = ViewStorageContext)] pub struct CounterState { pub value: RegisterView<u64>, }
rust
Apache-2.0
69f159d2106f7fc70870ce70074c55850bf1303b
2026-01-04T15:33:08.660695Z
false
linera-io/linera-protocol
https://github.com/linera-io/linera-protocol/blob/69f159d2106f7fc70870ce70074c55850bf1303b/examples/counter/src/service.rs
examples/counter/src/service.rs
// Copyright (c) Zefchain Labs, Inc. // SPDX-License-Identifier: Apache-2.0 #![cfg_attr(target_arch = "wasm32", no_main)] mod state; use std::sync::Arc; use async_graphql::{EmptySubscription, Object, Request, Response, Schema}; use counter::CounterOperation; use linera_sdk::{linera_base_types::WithServiceAbi, views::View, Service, ServiceRuntime}; use self::state::CounterState; pub struct CounterService { state: Arc<CounterState>, runtime: Arc<ServiceRuntime<Self>>, } linera_sdk::service!(CounterService); impl WithServiceAbi for CounterService { type Abi = counter::CounterAbi; } impl Service for CounterService { type Parameters = (); async fn new(runtime: ServiceRuntime<Self>) -> Self { let state = CounterState::load(runtime.root_view_storage_context()) .await .expect("Failed to load state"); CounterService { state: Arc::new(state), runtime: Arc::new(runtime), } } async fn handle_query(&self, request: Request) -> Response { let schema = Schema::build( self.state.clone(), MutationRoot { runtime: self.runtime.clone(), }, EmptySubscription, ) .finish(); schema.execute(request).await } } struct MutationRoot { runtime: Arc<ServiceRuntime<CounterService>>, } #[Object] impl MutationRoot { async fn increment(&self, value: u64) -> [u8; 0] { let operation = CounterOperation::Increment { value }; self.runtime.schedule_operation(&operation); [] } } #[cfg(test)] mod tests { use std::sync::Arc; use async_graphql::{Request, Response, Value}; use futures::FutureExt as _; use linera_sdk::{util::BlockingWait, views::View, Service, ServiceRuntime}; use serde_json::json; use super::{CounterService, CounterState}; #[test] fn query() { let value = 61_098_721_u64; let runtime = Arc::new(ServiceRuntime::<CounterService>::new()); let mut state = CounterState::load(runtime.root_view_storage_context()) .blocking_wait() .expect("Failed to read from mock key value store"); state.value.set(value); let service = CounterService { state: Arc::new(state), runtime, }; let request = Request::new("{ value }"); let response = service .handle_query(request) .now_or_never() .expect("Query should not await anything"); let expected = Response::new(Value::from_json(json!({"value" : 61_098_721})).unwrap()); assert_eq!(response, expected) } }
rust
Apache-2.0
69f159d2106f7fc70870ce70074c55850bf1303b
2026-01-04T15:33:08.660695Z
false
linera-io/linera-protocol
https://github.com/linera-io/linera-protocol/blob/69f159d2106f7fc70870ce70074c55850bf1303b/examples/counter/tests/single_chain.rs
examples/counter/tests/single_chain.rs
// Copyright (c) Zefchain Labs, Inc. // SPDX-License-Identifier: Apache-2.0 //! Integration tests for the Counter application. #![cfg(not(target_arch = "wasm32"))] use counter::CounterOperation; use linera_sdk::test::{QueryOutcome, TestValidator}; /// Test setting a counter and testing its coherency across microchains. /// /// Creates the application on a `chain`, initializing it with a 42 then adds 15 and obtains 57. /// which is then checked. #[tokio::test(flavor = "multi_thread")] async fn single_chain_test() { let (validator, module_id) = TestValidator::with_current_module::<counter::CounterAbi, (), u64>().await; let mut chain = validator.new_chain().await; let initial_state = 42u64; let application_id = chain .create_application(module_id, (), initial_state, vec![]) .await; let increment = 15u64; let operation = CounterOperation::Increment { value: increment }; chain .add_block(|block| { block.with_operation(application_id, operation); }) .await; let final_value = initial_state + increment; let QueryOutcome { response, .. } = chain.graphql_query(application_id, "query { value }").await; let state_value = response["value"].as_u64().expect("Failed to get the u64"); assert_eq!(state_value, final_value); }
rust
Apache-2.0
69f159d2106f7fc70870ce70074c55850bf1303b
2026-01-04T15:33:08.660695Z
false
linera-io/linera-protocol
https://github.com/linera-io/linera-protocol/blob/69f159d2106f7fc70870ce70074c55850bf1303b/examples/how-to/perform-http-requests/src/test_http_server.rs
examples/how-to/perform-http-requests/src/test_http_server.rs
// Copyright (c) Zefchain Labs, Inc. // SPDX-License-Identifier: Apache-2.0 //! A simple HTTP server binary to use in the README test. #![cfg_attr(target_arch = "wasm32", no_main)] #![cfg(not(target_arch = "wasm32"))] use std::{env, future::IntoFuture as _, net::Ipv4Addr}; use anyhow::anyhow; use axum::{routing::get, Router}; use tokio::net::TcpListener; /// The HTTP response expected by the contract. const HTTP_RESPONSE_BODY: &str = "Hello, world!"; /// Runs an HTTP server that simple responds with the request expected by the contract. #[tokio::main] async fn main() -> anyhow::Result<()> { let port = env::args() .nth(1) .ok_or_else(|| anyhow!("Missing listen port argument"))? .parse()?; let listener = TcpListener::bind((Ipv4Addr::from([127, 0, 0, 1]), port)).await?; let router = Router::new().route("/", get(|| async { HTTP_RESPONSE_BODY })); axum::serve(listener, router).into_future().await?; Ok(()) }
rust
Apache-2.0
69f159d2106f7fc70870ce70074c55850bf1303b
2026-01-04T15:33:08.660695Z
false
linera-io/linera-protocol
https://github.com/linera-io/linera-protocol/blob/69f159d2106f7fc70870ce70074c55850bf1303b/examples/how-to/perform-http-requests/src/contract.rs
examples/how-to/perform-http-requests/src/contract.rs
// Copyright (c) Zefchain Labs, Inc. // SPDX-License-Identifier: Apache-2.0 #![cfg_attr(target_arch = "wasm32", no_main)] use how_to_perform_http_requests::{Abi, Operation}; use linera_sdk::{http, linera_base_types::WithContractAbi, Contract as _, ContractRuntime}; pub struct Contract { runtime: ContractRuntime<Self>, } linera_sdk::contract!(Contract); impl WithContractAbi for Contract { type Abi = Abi; } impl linera_sdk::Contract for Contract { type Message = (); type InstantiationArgument = (); type Parameters = String; type EventValue = (); async fn load(runtime: ContractRuntime<Self>) -> Self { Contract { runtime } } async fn instantiate(&mut self, (): Self::InstantiationArgument) { // Check that the global parameters can be deserialized correctly. self.runtime.application_parameters(); } async fn execute_operation(&mut self, operation: Self::Operation) -> Self::Response { match operation { Operation::HandleHttpResponse(response_body) => { self.handle_http_response(response_body) } Operation::PerformHttpRequest => self.perform_http_request(), Operation::UseServiceAsOracle => self.use_service_as_oracle(), } } async fn execute_message(&mut self, (): Self::Message) { panic!("This application doesn't support any cross-chain messages"); } async fn store(self) {} } impl Contract { /// Handles an HTTP response, ensuring it is valid. /// /// Because the `response_body` can come from outside the contract in an /// [`Operation::HandleHttpResponse`], it could be forged. Therefore, the contract should /// assume that the `response_body` is untrusted, and should perform validation and /// verification steps to ensure that the `response_body` is real and can be trusted. /// /// Usually this is done by verifying that the response is signed by the trusted HTTP server. /// In this example, the verification is simulated by checking that the `response_body` is /// exactly an expected value. fn handle_http_response(&self, response_body: Vec<u8>) { assert_eq!(response_body, b"Hello, world!"); } /// Performs an HTTP request directly in the contract. /// /// This only works if the HTTP response (including any HTTP headers the response contains) is /// the same in a quorum of validators. Otherwise, the contract should call the service as an /// oracle to perform the HTTP request and the service should only return the data that will be /// the same in a quorum of validators. fn perform_http_request(&mut self) { let url = self.runtime.application_parameters(); let response = self.runtime.http_request(http::Request::get(url)); self.handle_http_response(response.body); } /// Uses the service as an oracle to perform the HTTP request. /// /// The service can then receive a non-deterministic response and return to the contract a /// deterministic response. fn use_service_as_oracle(&mut self) { let application_id = self.runtime.application_id(); let request = async_graphql::Request::new("query { performHttpRequest }"); let graphql_response = self.runtime.query_service(application_id, &request); let async_graphql::Value::Object(graphql_response_data) = graphql_response.data else { panic!("Unexpected response from service: {graphql_response:#?}"); }; let async_graphql::Value::List(ref http_response_list) = graphql_response_data["performHttpRequest"] else { panic!( "Unexpected response for service's `performHttpRequest` query: {:#?}", graphql_response_data ); }; let http_response = http_response_list .iter() .map(|value| { let async_graphql::Value::Number(number) = value else { panic!("Unexpected type in HTTP request body's bytes: {value:#?}"); }; number .as_i64() .and_then(|integer| u8::try_from(integer).ok()) .unwrap_or_else(|| { panic!("Unexpected value in HTTP request body's bytes: {number:#?}") }) }) .collect(); self.handle_http_response(http_response); } } #[path = "unit_tests/contract.rs"] mod unit_tests;
rust
Apache-2.0
69f159d2106f7fc70870ce70074c55850bf1303b
2026-01-04T15:33:08.660695Z
false
linera-io/linera-protocol
https://github.com/linera-io/linera-protocol/blob/69f159d2106f7fc70870ce70074c55850bf1303b/examples/how-to/perform-http-requests/src/lib.rs
examples/how-to/perform-http-requests/src/lib.rs
// Copyright (c) Zefchain Labs, Inc. // SPDX-License-Identifier: Apache-2.0 //! ABI of the Counter Example Application use async_graphql::{Request, Response}; use linera_sdk::abi::{ContractAbi, ServiceAbi}; use serde::{Deserialize, Serialize}; /// The marker type that connects the types used to interface with the application. pub struct Abi; impl ContractAbi for Abi { type Operation = Operation; type Response = (); } impl ServiceAbi for Abi { type Query = Request; type QueryResponse = Response; } /// Operations that the contract can handle. #[derive(Debug, Deserialize, Eq, PartialEq, Serialize)] pub enum Operation { /// Handles the HTTP response of a request made outside the contract. HandleHttpResponse(Vec<u8>), /// Performs an HTTP request inside the contract. PerformHttpRequest, /// Requests the service to perform the HTTP request as an oracle. UseServiceAsOracle, }
rust
Apache-2.0
69f159d2106f7fc70870ce70074c55850bf1303b
2026-01-04T15:33:08.660695Z
false
linera-io/linera-protocol
https://github.com/linera-io/linera-protocol/blob/69f159d2106f7fc70870ce70074c55850bf1303b/examples/how-to/perform-http-requests/src/service.rs
examples/how-to/perform-http-requests/src/service.rs
// Copyright (c) Zefchain Labs, Inc. // SPDX-License-Identifier: Apache-2.0 #![cfg_attr(target_arch = "wasm32", no_main)] use std::sync::Arc; use async_graphql::{EmptySubscription, Request, Response, Schema}; use how_to_perform_http_requests::{Abi, Operation}; use linera_sdk::{ensure, http, linera_base_types::WithServiceAbi, Service as _, ServiceRuntime}; #[derive(Clone)] pub struct Service { runtime: Arc<ServiceRuntime<Self>>, } linera_sdk::service!(Service); impl WithServiceAbi for Service { type Abi = Abi; } impl linera_sdk::Service for Service { type Parameters = String; async fn new(runtime: ServiceRuntime<Self>) -> Self { Service { runtime: Arc::new(runtime), } } async fn handle_query(&self, request: Request) -> Response { let schema = Schema::build( Query { service: self.clone(), }, Mutation { service: self.clone(), }, EmptySubscription, ) .finish(); schema.execute(request).await } } /// The handler for service queries. struct Query { service: Service, } #[async_graphql::Object] impl Query { /// Performs an HTTP query in the service, and returns the response body if the status /// code is OK. /// /// Note that any headers in the response are discarded. pub async fn perform_http_request(&self) -> async_graphql::Result<Vec<u8>> { self.service.perform_http_request() } } impl Service { /// Performs an HTTP query in the service, and returns the response body if the status /// code is OK. /// /// Note that any headers in the response are discarded. pub fn perform_http_request(&self) -> async_graphql::Result<Vec<u8>> { let url = self.runtime.application_parameters(); let response = self.runtime.http_request(http::Request::get(url)); ensure!( response.status == 200, async_graphql::Error::new(format!( "HTTP request failed with status code {}", response.status )) ); Ok(response.body) } } /// The handler for service mutations. struct Mutation { service: Service, } #[async_graphql::Object] impl Mutation { /// Performs an HTTP query in the service, and sends the response to the contract by scheduling /// an [`Operation::HandleHttpResponse`]. pub async fn perform_http_request(&self) -> async_graphql::Result<bool> { let response = self.service.perform_http_request()?; self.service .runtime .schedule_operation(&Operation::HandleHttpResponse(response)); Ok(true) } /// Requests the contract to perform an HTTP request, by scheduling an /// [`Operation::PerformHttpRequest`]. pub async fn perform_http_request_in_contract(&self) -> async_graphql::Result<bool> { self.service .runtime .schedule_operation(&Operation::PerformHttpRequest); Ok(true) } /// Requests the contract to use this service as an oracle to perform an HTTP request, by /// scheduling an [`Operation::PerformHttpRequest`]. pub async fn perform_http_request_as_oracle(&self) -> async_graphql::Result<bool> { self.service .runtime .schedule_operation(&Operation::UseServiceAsOracle); Ok(true) } } #[path = "unit_tests/service.rs"] mod unit_tests;
rust
Apache-2.0
69f159d2106f7fc70870ce70074c55850bf1303b
2026-01-04T15:33:08.660695Z
false
linera-io/linera-protocol
https://github.com/linera-io/linera-protocol/blob/69f159d2106f7fc70870ce70074c55850bf1303b/examples/how-to/perform-http-requests/src/unit_tests/contract.rs
examples/how-to/perform-http-requests/src/unit_tests/contract.rs
// Copyright (c) Zefchain Labs, Inc. // SPDX-License-Identifier: Apache-2.0 #![cfg(test)] //! Unit tests for the contract. use how_to_perform_http_requests::{Abi, Operation}; use linera_sdk::{ http, linera_base_types::ApplicationId, util::BlockingWait as _, Contract as _, ContractRuntime, }; use super::Contract; /// Tests if the contract accepts a valid HTTP response obtained off-chain. /// /// The contract should not panic if it receives a HTTP response that it can trust. In /// this example application, that just means an HTTP response exactly to one the contract /// expects, but in most applications this would involve signing the response in the HTTP /// server and checking the signature in the contract. #[test] fn accepts_valid_off_chain_response() { let mut contract = create_contract(); contract .execute_operation(Operation::HandleHttpResponse(b"Hello, world!".to_vec())) .blocking_wait(); } /// Tests if the contract rejects an invalid HTTP response obtained off-chain. /// /// The contract should panic if it receives a HTTP response that it can't trust. In /// this example application, that just means an HTTP response different from one it /// expects, but in most applications this would involve checking the signature of the /// response to see if it was signed by a trusted party that created the response. #[test] #[should_panic(expected = "assertion `left == right` failed")] fn rejects_invalid_off_chain_response() { let mut contract = create_contract(); contract .execute_operation(Operation::HandleHttpResponse(b"Fake response".to_vec())) .blocking_wait(); } /// Tests if the contract performs an HTTP request and accepts it if it receives a valid /// response. #[test] fn accepts_response_obtained_by_contract() { let url = "http://some.test.url".to_owned(); let mut contract = create_contract(); contract .runtime .set_application_parameters(url.clone()) .add_expected_http_request( http::Request::get(url), http::Response::ok(b"Hello, world!".to_vec()), ); contract .execute_operation(Operation::PerformHttpRequest) .blocking_wait(); } /// Tests if the contract performs an HTTP request and rejects it if it receives an /// invalid response. #[test] #[should_panic(expected = "assertion `left == right` failed")] fn rejects_invalid_response_obtained_by_contract() { let url = "http://some.test.url".to_owned(); let mut contract = create_contract(); contract .runtime .set_application_parameters(url.clone()) .add_expected_http_request( http::Request::get(url), http::Response::ok(b"Untrusted response".to_vec()), ); contract .execute_operation(Operation::PerformHttpRequest) .blocking_wait(); } /// Tests if the contract uses the service as an oracle to perform an HTTP request and /// accepts the response if it's valid. #[test] fn accepts_response_from_oracle() { let application_id = ApplicationId::default().with_abi::<Abi>(); let url = "http://some.test.url".to_owned(); let mut contract = create_contract(); let http_response_graphql_list = "Hello, world!" .as_bytes() .iter() .map(|&byte| async_graphql::Value::Number(byte.into())) .collect(); contract .runtime .set_application_id(application_id) .set_application_parameters(url.clone()) .add_expected_service_query( application_id, async_graphql::Request::new("query { performHttpRequest }"), async_graphql::Response::new(async_graphql::Value::Object( [( async_graphql::Name::new("performHttpRequest"), async_graphql::Value::List(http_response_graphql_list), )] .into(), )), ); contract .execute_operation(Operation::UseServiceAsOracle) .blocking_wait(); } /// Tests if the contract uses the service as an oracle to perform an HTTP request and /// rejects the response if it's invalid. #[test] #[should_panic(expected = "assertion `left == right` failed")] fn rejects_invalid_response_from_oracle() { let application_id = ApplicationId::default().with_abi::<Abi>(); let url = "http://some.test.url".to_owned(); let mut contract = create_contract(); let http_response_graphql_list = "Invalid response" .as_bytes() .iter() .map(|&byte| async_graphql::Value::Number(byte.into())) .collect(); contract .runtime .set_application_id(application_id) .set_application_parameters(url.clone()) .add_expected_service_query( application_id, async_graphql::Request::new("query { performHttpRequest }"), async_graphql::Response::new(async_graphql::Value::Object( [( async_graphql::Name::new("performHttpRequest"), async_graphql::Value::List(http_response_graphql_list), )] .into(), )), ); contract .execute_operation(Operation::UseServiceAsOracle) .blocking_wait(); } /// Creates a [`Contract`] instance for testing. fn create_contract() -> Contract { let runtime = ContractRuntime::new(); Contract { runtime } }
rust
Apache-2.0
69f159d2106f7fc70870ce70074c55850bf1303b
2026-01-04T15:33:08.660695Z
false
linera-io/linera-protocol
https://github.com/linera-io/linera-protocol/blob/69f159d2106f7fc70870ce70074c55850bf1303b/examples/how-to/perform-http-requests/src/unit_tests/service.rs
examples/how-to/perform-http-requests/src/unit_tests/service.rs
// Copyright (c) Zefchain Labs, Inc. // SPDX-License-Identifier: Apache-2.0 #![cfg(test)] //! Unit tests for the service. use std::sync::Arc; use assert_matches::assert_matches; use how_to_perform_http_requests::Operation; use linera_sdk::{http, util::BlockingWait, Service as _, ServiceRuntime}; use super::Service; /// A dummy URL to use in the tests. const TEST_BASE_URL: &str = "http://some.test.url"; /// Tests if an HTTP request is performed by a service query. #[test] fn service_query_performs_http_request() { let http_response = b"Hello, world!"; let mut service = create_service(); let runtime = Arc::get_mut(&mut service.runtime).expect("Runtime should not be shared"); runtime.add_expected_http_request( http::Request::get(TEST_BASE_URL), http::Response::ok(http_response), ); let request = async_graphql::Request::new("query { performHttpRequest }"); let response = service.handle_query(request).blocking_wait(); let response_bytes = extract_response_bytes(response); assert_eq!(response_bytes, http_response); } /// Tests if a failed HTTP request performed by a service query leads to a GraphQL error. #[test] fn service_query_returns_http_request_error() { let mut service = create_service(); let runtime = Arc::get_mut(&mut service.runtime).expect("Runtime should not be shared"); runtime.add_expected_http_request( http::Request::get(TEST_BASE_URL), http::Response::unauthorized(), ); let request = async_graphql::Request::new("query { performHttpRequest }"); let response = service.handle_query(request).blocking_wait(); let error = extract_error_string(response); assert_eq!(error, "HTTP request failed with status code 401"); } /// Tests if the service sends the HTTP response to the contract. #[test] fn service_sends_http_response_to_contract() { let http_response = b"Hello, contract!"; let mut service = create_service(); let runtime = Arc::get_mut(&mut service.runtime).expect("Runtime should not be shared"); runtime.add_expected_http_request( http::Request::get(TEST_BASE_URL), http::Response::ok(http_response), ); let request = async_graphql::Request::new("mutation { performHttpRequest }"); service.handle_query(request).blocking_wait(); let operations = service.runtime.scheduled_operations::<Operation>(); assert_eq!( operations, vec![Operation::HandleHttpResponse(http_response.to_vec())] ); } /// Tests if the service requests the contract to perform an HTTP request. #[test] fn service_requests_contract_to_perform_http_request() { let service = create_service(); let request = async_graphql::Request::new("mutation { performHttpRequestInContract }"); service.handle_query(request).blocking_wait(); let operations = service.runtime.scheduled_operations::<Operation>(); assert_eq!(operations, vec![Operation::PerformHttpRequest]); } /// Tests if the service requests the contract to use the service as an oracle to perform an HTTP /// request. #[test] fn service_requests_contract_to_use_it_as_an_oracle() { let service = create_service(); let request = async_graphql::Request::new("mutation { performHttpRequestAsOracle }"); service.handle_query(request).blocking_wait(); let operations = service.runtime.scheduled_operations::<Operation>(); assert_eq!(operations, vec![Operation::UseServiceAsOracle]); } /// Creates a [`Service`] instance for testing. fn create_service() -> Service { let runtime = ServiceRuntime::new().with_application_parameters(TEST_BASE_URL.to_owned()); Service { runtime: Arc::new(runtime), } } /// Extracts the HTTP response bytes from an [`async_graphql::Response`]. fn extract_response_bytes(response: async_graphql::Response) -> Vec<u8> { assert!(response.errors.is_empty()); let async_graphql::Value::Object(response_data) = response.data else { panic!("Unexpected response from service: {response:#?}"); }; let async_graphql::Value::List(ref response_list) = response_data["performHttpRequest"] else { panic!("Unexpected response for `performHttpRequest` query: {response_data:#?}"); }; response_list .iter() .map(|value| { let async_graphql::Value::Number(ref number) = value else { panic!("Unexpected value in response list: {value:#?}"); }; number .as_i64() .expect("Invalid integer in response list: {number:#?}") .try_into() .expect("Invalid byte in response list: {number:#?}") }) .collect() } /// Extracts the GraphQL error message from an [`async_graphql::Response`]. fn extract_error_string(response: async_graphql::Response) -> String { assert_matches!(response.data, async_graphql::Value::Null); let mut errors = response.errors; assert_eq!( errors.len(), 1, "Unexpected error list from service: {errors:#?}" ); errors .pop() .expect("There should be exactly one error, as asserted above") .message }
rust
Apache-2.0
69f159d2106f7fc70870ce70074c55850bf1303b
2026-01-04T15:33:08.660695Z
false
linera-io/linera-protocol
https://github.com/linera-io/linera-protocol/blob/69f159d2106f7fc70870ce70074c55850bf1303b/examples/how-to/perform-http-requests/tests/http_requests.rs
examples/how-to/perform-http-requests/tests/http_requests.rs
// Copyright (c) Zefchain Labs, Inc. // SPDX-License-Identifier: Apache-2.0 //! Integration tests that perform real HTTP requests to a local HTTP server. #![cfg(not(target_arch = "wasm32"))] use assert_matches::assert_matches; use axum::{routing::get, Router}; use how_to_perform_http_requests::Abi; use linera_sdk::test::{ ExecutionError, HttpServer, QueryOutcome, TestValidator, WasmExecutionError, }; /// Tests if service query performs HTTP request to allowed host. #[test_log::test(tokio::test)] async fn service_query_performs_http_request() -> anyhow::Result<()> { const HTTP_RESPONSE_BODY: &str = "Hello, world!"; let http_server = HttpServer::start(Router::new().route("/", get(|| async { HTTP_RESPONSE_BODY }))).await?; let port = http_server.port(); let url = format!("http://localhost:{port}/"); let (mut validator, application_id, chain) = TestValidator::with_current_application::<Abi, _, _>(url, ()).await; validator .change_resource_control_policy(|policy| { policy .http_request_allow_list .insert("localhost".to_owned()); }) .await; let QueryOutcome { response, .. } = chain .graphql_query(application_id, "query { performHttpRequest }") .await; let Some(byte_list) = response["performHttpRequest"].as_array() else { panic!("Expected a list of bytes representing the response body, got {response:#}"); }; let bytes = byte_list .iter() .map(|value| { value .as_i64() .ok_or(()) .and_then(|integer| integer.try_into().map_err(|_| ())) }) .collect::<Result<Vec<u8>, _>>() .unwrap_or_else(|()| { panic!("Expected a list of bytes representing the response body, got {byte_list:#?}") }); assert_eq!(bytes, HTTP_RESPONSE_BODY.as_bytes()); Ok(()) } /// Tests if service query can't perform HTTP requests to hosts that aren't allowed. #[test_log::test(tokio::test)] async fn service_query_cant_send_http_request_to_unauthorized_host() { let url = "http://localhost/"; let (_validator, application_id, chain) = TestValidator::with_current_application::<Abi, _, _>(url.to_owned(), ()).await; let error = chain .try_graphql_query(application_id, "query { performHttpRequest }") .await .expect_err("Expected GraphQL query to fail"); assert_matches!( error.expect_execution_error(), ExecutionError::UnauthorizedHttpRequest(attempted_url) if attempted_url.to_string() == url ); } /// Tests if the service sends a valid HTTP response to the contract. #[test_log::test(tokio::test)] async fn service_sends_valid_http_response_to_contract() -> anyhow::Result<()> { const HTTP_RESPONSE_BODY: &str = "Hello, world!"; let http_server = HttpServer::start(Router::new().route("/", get(|| async { HTTP_RESPONSE_BODY }))).await?; let port = http_server.port(); let url = format!("http://localhost:{port}/"); let (mut validator, application_id, chain) = TestValidator::with_current_application::<Abi, _, _>(url, ()).await; validator .change_resource_control_policy(|policy| { policy .http_request_allow_list .insert("localhost".to_owned()); }) .await; chain .graphql_mutation(application_id, "mutation { performHttpRequest }") .await; Ok(()) } /// Tests if the contract rejects an invalid HTTP response sent by the service. #[test_log::test(tokio::test)] async fn contract_rejects_invalid_http_response_from_service() { const HTTP_RESPONSE_BODY: &str = "Untrusted response"; let http_server = HttpServer::start(Router::new().route("/", get(|| async { HTTP_RESPONSE_BODY }))) .await .expect("Failed to start test HTTP server"); let port = http_server.port(); let url = format!("http://localhost:{port}/"); let (mut validator, application_id, chain) = TestValidator::with_current_application::<Abi, _, _>(url.clone(), ()).await; validator .change_resource_control_policy(|policy| { policy .http_request_allow_list .insert("localhost".to_owned()); }) .await; let error = chain .try_graphql_mutation(application_id, "mutation { performHttpRequest }") .await .expect_err("Expected GraphQL mutation to fail"); assert_matches!( error.expect_proposal_execution_error(0), ExecutionError::WasmError(WasmExecutionError::ExecuteModule(_)) ); } /// Tests if the contract accepts a valid HTTP response it obtains by itself. #[test_log::test(tokio::test)] async fn contract_accepts_valid_http_response_it_obtains_by_itself() -> anyhow::Result<()> { const HTTP_RESPONSE_BODY: &str = "Hello, world!"; let http_server = HttpServer::start(Router::new().route("/", get(|| async { HTTP_RESPONSE_BODY }))).await?; let port = http_server.port(); let url = format!("http://localhost:{port}/"); let (mut validator, application_id, chain) = TestValidator::with_current_application::<Abi, _, _>(url, ()).await; validator .change_resource_control_policy(|policy| { policy .http_request_allow_list .insert("localhost".to_owned()); }) .await; chain .graphql_mutation(application_id, "mutation { performHttpRequestInContract }") .await; Ok(()) } /// Tests if the contract rejects an invalid HTTP response it obtains by itself. #[test_log::test(tokio::test)] async fn contract_rejects_invalid_http_response_it_obtains_by_itself() { const HTTP_RESPONSE_BODY: &str = "Untrusted response"; let http_server = HttpServer::start(Router::new().route("/", get(|| async { HTTP_RESPONSE_BODY }))) .await .expect("Failed to start test HTTP server"); let port = http_server.port(); let url = format!("http://localhost:{port}/"); let (mut validator, application_id, chain) = TestValidator::with_current_application::<Abi, _, _>(url, ()).await; validator .change_resource_control_policy(|policy| { policy .http_request_allow_list .insert("localhost".to_owned()); }) .await; let error = chain .try_graphql_mutation(application_id, "mutation { performHttpRequestInContract }") .await .expect_err("Expected GraphQL mutation to fail"); assert_matches!( error.expect_proposal_execution_error(0), ExecutionError::WasmError(WasmExecutionError::ExecuteModule(_)) ); } /// Tests if the contract accepts a valid HTTP response it obtains from the service acting as an /// oracle. #[test_log::test(tokio::test)] async fn contract_accepts_valid_http_response_from_oracle() -> anyhow::Result<()> { const HTTP_RESPONSE_BODY: &str = "Hello, world!"; let http_server = HttpServer::start(Router::new().route("/", get(|| async { HTTP_RESPONSE_BODY }))).await?; let port = http_server.port(); let url = format!("http://localhost:{port}/"); let (mut validator, application_id, chain) = TestValidator::with_current_application::<Abi, _, _>(url, ()).await; validator .change_resource_control_policy(|policy| { policy .http_request_allow_list .insert("localhost".to_owned()); }) .await; chain .graphql_mutation(application_id, "mutation { performHttpRequestAsOracle }") .await; Ok(()) } /// Tests if the contract rejects an invalid HTTP response it obtains from the service acting as an /// oracle. #[test_log::test(tokio::test)] async fn contract_rejects_invalid_http_response_from_oracle() { const HTTP_RESPONSE_BODY: &str = "Invalid response"; let http_server = HttpServer::start(Router::new().route("/", get(|| async { HTTP_RESPONSE_BODY }))) .await .expect("Failed to start test HTTP server"); let port = http_server.port(); let url = format!("http://localhost:{port}/"); let (mut validator, application_id, chain) = TestValidator::with_current_application::<Abi, _, _>(url, ()).await; validator .change_resource_control_policy(|policy| { policy .http_request_allow_list .insert("localhost".to_owned()); }) .await; let error = chain .try_graphql_mutation(application_id, "mutation { performHttpRequestAsOracle }") .await .expect_err("Expected GraphQL mutation to fail"); assert_matches!( error.expect_proposal_execution_error(0), ExecutionError::WasmError(WasmExecutionError::ExecuteModule(_)) ); }
rust
Apache-2.0
69f159d2106f7fc70870ce70074c55850bf1303b
2026-01-04T15:33:08.660695Z
false
linera-io/linera-protocol
https://github.com/linera-io/linera-protocol/blob/69f159d2106f7fc70870ce70074c55850bf1303b/examples/how-to/perform-http-requests/tests/http_server/mod.rs
examples/how-to/perform-http-requests/tests/http_server/mod.rs
// Copyright (c) Zefchain Labs, Inc. // SPDX-License-Identifier: Apache-2.0 //! A simple HTTP server to use for testing. use std::{future::IntoFuture, net::Ipv4Addr}; use axum::Router; use futures::FutureExt as _; use tokio::{net::TcpListener, sync::oneshot}; /// A handle to a running HTTP server. /// /// The server is gracefully shutdown when this handle is dropped. pub struct HttpServer { port: u16, _shutdown_sender: oneshot::Sender<()>, } impl HttpServer { /// Spawns a task with an HTTP server serving the routes defined by the [`Router`]. /// /// Returns a [`HttpServer`] handle to keep the server running in the background. pub async fn start(router: Router) -> anyhow::Result<Self> { let (shutdown_sender, shutdown_receiver) = oneshot::channel(); let shutdown_signal = shutdown_receiver.map(|_| ()); let listener = TcpListener::bind((Ipv4Addr::from([127, 0, 0, 1]), 0)).await?; let port = listener.local_addr()?.port(); tokio::spawn( axum::serve(listener, router) .with_graceful_shutdown(shutdown_signal) .into_future(), ); Ok(HttpServer { port, _shutdown_sender: shutdown_sender, }) } /// Returns the port this HTTP server is listening on. pub fn port(&self) -> u16 { self.port } }
rust
Apache-2.0
69f159d2106f7fc70870ce70074c55850bf1303b
2026-01-04T15:33:08.660695Z
false
linera-io/linera-protocol
https://github.com/linera-io/linera-protocol/blob/69f159d2106f7fc70870ce70074c55850bf1303b/examples/agent/src/main.rs
examples/agent/src/main.rs
// Copyright (c) Zefchain Labs, Inc. // SPDX-License-Identifier: Apache-2.0 use std::{io, io::Write}; use anyhow::Result; use clap::Parser; use reqwest::Client; use rig::{ agent::AgentBuilder, completion::{Chat, Message, ToolDefinition}, providers::openai, tool::Tool, }; use serde::{Deserialize, Serialize}; use serde_json::json; use url::Url; const INTROSPECTION_QUERY: &str = r#" query IntrospectionQuery { __schema { queryType { name } mutationType { name } types { ...FullType } } } fragment FullType on __Type { kind name description fields(includeDeprecated: false) { name description args { ...InputValue } type { ...TypeRef } } inputFields { ...InputValue } interfaces { ...TypeRef } enumValues(includeDeprecated: true) { name description } possibleTypes { ...TypeRef } } fragment InputValue on __InputValue { name description type { ...TypeRef } defaultValue } fragment TypeRef on __Type { kind name ofType { kind name ofType { kind name ofType { kind name ofType { kind name ofType { kind name ofType { kind name ofType { kind name ofType { kind name ofType { kind name } } } } } } } } } } "#; const PREAMBLE: &str = r#" You are a bot that works and interacts with the Linera blockchain via a Linera wallet. Even though you're going to be using mostly GraphQL, try to use natural language as much as possible to speak to the user. If you are not certain on a given instruction, ask for clarification. "#; const LINERA_CONTEXT: &str = r#" Linera is a decentralized infrastructure optimized for Web3 applications requiring guaranteed performance for unlimited active users. It introduces "microchains," lightweight blockchains running in parallel within a single validator set. Each user operates their own microchain, adding blocks as needed, which ensures efficient, elastic scalability. In Linera, user wallets manage their microchains, allowing owners to control block additions and contents. Validators ensure block validity, verifying operations like asset transfers and incoming messages. Applications are WebAssembly (Wasm) programs with distinct states on each chain, facilitating asynchronous cross-chain communication. Linera's architecture is ideal for applications requiring real-time transactions among numerous users, such as micro-payments, social data feeds, and turn-based games. By embedding full nodes into user wallets, typically as browser extensions, Linera enables direct state queries and enhances security without relying on external APIs or light clients. "#; #[derive(Parser, Debug)] #[command( name = "Linera Agent", about = "An AI agent which uses LLMs to interface with Linera." )] struct Opt { /// OpenAI model the agent should use. #[arg(long, default_value = "gpt-4o")] model: String, /// Linera node service URL. #[arg(long, default_value = "http://localhost:8080")] node_service_url: String, } #[tokio::main] async fn main() { let opt = Opt::parse(); let openai = openai::Client::from_env(); let model = openai.completion_model(&opt.model); let node_service = LineraNodeService::new(opt.node_service_url.parse().unwrap()).unwrap(); let graphql_def = node_service.get_graphql_definition().await.unwrap(); let graphql_context = format!( "This is the GraphQL schema for interfacing with the Linera service: {}", graphql_def ); // Configure the agent let agent = AgentBuilder::new(model) .preamble(PREAMBLE) .context(LINERA_CONTEXT) .context(&graphql_context) .tool(node_service) .build(); chat(agent).await; } #[derive(Deserialize)] struct NodeServiceArgs { input: String, } #[derive(Serialize, Deserialize)] struct NodeServiceOutput { data: serde_json::Value, errors: Option<Vec<serde_json::Value>>, } struct LineraNodeService { url: Url, client: Client, } impl LineraNodeService { fn new(url: Url) -> Result<Self> { Ok(Self { url, client: Client::new(), }) } async fn get_graphql_definition(&self) -> Result<String> { let response = self .client .post(self.url.clone()) .json(&json!({ "operationName": "IntrospectionQuery", "query": INTROSPECTION_QUERY })) .send() .await?; Ok(response.text().await?) } } impl Tool for LineraNodeService { const NAME: &'static str = "Linera"; type Error = reqwest::Error; type Args = NodeServiceArgs; // GraphQL type Output = NodeServiceOutput; // More GraphQL async fn definition(&self, _prompt: String) -> ToolDefinition { ToolDefinition { name: "Linera".to_string(), description: "Interact with a Linera wallet via GraphQL".to_string(), parameters: json!({ "type": "object", "properties": { "input": { "type": "string", "description": "The GraphQL query to use. This *must* be valid GraphQL and not JSON. Do not escape quotes." } } }), } } async fn call(&self, args: Self::Args) -> Result<Self::Output, Self::Error> { println!("Req: {}", args.input); let response = self .client .post(self.url.clone()) .json(&json!({ "query": args.input })) .send() .await?; response.json().await } } pub async fn chat(chatbot: impl Chat) { let stdin = io::stdin(); let mut stdout = io::stdout(); let mut chat_log = vec![]; println!("I'm the Linera agent. How can I help? (Type 'exit' to quit.)"); loop { print!("> "); // Flush stdout to ensure the prompt appears before input stdout.flush().unwrap(); let mut input = String::new(); match stdin.read_line(&mut input) { Ok(_) => { // Remove the newline character from the input let input = input.trim(); if input == "exit" { break; } match chatbot.chat(input, chat_log.clone()).await { Ok(response) => { chat_log.push(Message::user(input)); chat_log.push(Message::assistant(response.clone())); println!( "========================== Response ============================" ); println!("{response}"); println!( "================================================================\n\n" ); } Err(e) => { eprintln!("Error: {}", e); continue; } } } Err(error) => println!("Error reading input: {}", error), } } }
rust
Apache-2.0
69f159d2106f7fc70870ce70074c55850bf1303b
2026-01-04T15:33:08.660695Z
false
linera-io/linera-protocol
https://github.com/linera-io/linera-protocol/blob/69f159d2106f7fc70870ce70074c55850bf1303b/examples/call-evm-counter/src/contract.rs
examples/call-evm-counter/src/contract.rs
// Copyright (c) Zefchain Labs, Inc. // SPDX-License-Identifier: Apache-2.0 #![cfg_attr(target_arch = "wasm32", no_main)] use alloy_primitives::{address, U256}; use alloy_sol_types::{sol, SolCall}; use call_evm_counter::{CallCounterAbi, CallCounterOperation}; use linera_sdk::{ abis::evm::EvmAbi, linera_base_types::{Amount, ApplicationId, EvmOperation, WithContractAbi}, Contract, ContractRuntime, }; pub struct CallCounterContract { runtime: ContractRuntime<Self>, } linera_sdk::contract!(CallCounterContract); impl WithContractAbi for CallCounterContract { type Abi = CallCounterAbi; } impl CallCounterContract { fn process_operation(&mut self, operation: Vec<u8>) -> u64 { let evm_counter_id = self.runtime.application_parameters(); let result = self .runtime .call_application(true, evm_counter_id, &operation); let arr: [u8; 32] = result.try_into().expect("result should have length 32"); U256::from_be_bytes(arr).to::<u64>() } } impl Contract for CallCounterContract { type Message = (); type InstantiationArgument = (); type Parameters = ApplicationId<EvmAbi>; type EventValue = (); async fn load(runtime: ContractRuntime<Self>) -> Self { CallCounterContract { runtime } } async fn instantiate(&mut self, _value: ()) { // Validate that the application parameters were configured correctly. self.runtime.application_parameters(); } async fn execute_operation(&mut self, operation: CallCounterOperation) -> u64 { sol! { function increment(uint64 input); function call_from_wasm(address remote_address); } match operation { CallCounterOperation::Increment(increment) => { let operation = incrementCall { input: increment }; let operation = EvmOperation::new(Amount::ZERO, operation.abi_encode()); let operation = operation.to_bytes().unwrap(); self.process_operation(operation) } CallCounterOperation::TestCallAddress => { let remote_address = address!("0000000000000000000000000000000000000000"); let operation = call_from_wasmCall { remote_address }; let operation = EvmOperation::new(Amount::ZERO, operation.abi_encode()); let operation = operation.to_bytes().unwrap(); self.process_operation(operation) } } } async fn execute_message(&mut self, _message: ()) { panic!("Counter application doesn't support any cross-chain messages"); } async fn store(self) {} }
rust
Apache-2.0
69f159d2106f7fc70870ce70074c55850bf1303b
2026-01-04T15:33:08.660695Z
false
linera-io/linera-protocol
https://github.com/linera-io/linera-protocol/blob/69f159d2106f7fc70870ce70074c55850bf1303b/examples/call-evm-counter/src/lib.rs
examples/call-evm-counter/src/lib.rs
// Copyright (c) Zefchain Labs, Inc. // SPDX-License-Identifier: Apache-2.0 /*! ABI of the Counter Example Application that does not use GraphQL */ use linera_sdk::linera_base_types::{ContractAbi, ServiceAbi}; use serde::{Deserialize, Serialize}; pub struct CallCounterAbi; impl ContractAbi for CallCounterAbi { type Operation = CallCounterOperation; type Response = u64; } impl ServiceAbi for CallCounterAbi { type Query = CallCounterRequest; type QueryResponse = u64; } #[derive(Debug, Serialize, Deserialize)] pub enum CallCounterRequest { Query, TestCallAddress, ContractTestCallAddress, Increment(u64), } #[derive(Debug, Serialize, Deserialize)] pub enum CallCounterOperation { TestCallAddress, Increment(u64), }
rust
Apache-2.0
69f159d2106f7fc70870ce70074c55850bf1303b
2026-01-04T15:33:08.660695Z
false
linera-io/linera-protocol
https://github.com/linera-io/linera-protocol/blob/69f159d2106f7fc70870ce70074c55850bf1303b/examples/call-evm-counter/src/service.rs
examples/call-evm-counter/src/service.rs
// Copyright (c) Zefchain Labs, Inc. // SPDX-License-Identifier: Apache-2.0 #![cfg_attr(target_arch = "wasm32", no_main)] use std::sync::Arc; use alloy_primitives::{address, U256}; use alloy_sol_types::{sol, SolCall}; use call_evm_counter::{CallCounterOperation, CallCounterRequest}; use linera_sdk::{ abis::evm::EvmAbi, linera_base_types::{ApplicationId, EvmQuery, WithServiceAbi}, Service, ServiceRuntime, }; pub struct CallCounterService { runtime: Arc<ServiceRuntime<Self>>, } linera_sdk::service!(CallCounterService); impl WithServiceAbi for CallCounterService { type Abi = call_evm_counter::CallCounterAbi; } impl CallCounterService { fn process_query(&self, query: Vec<u8>) -> u64 { let query = EvmQuery::Query(query); let evm_counter_id = self.runtime.application_parameters(); let result = self.runtime.query_application(evm_counter_id, &query); let arr: [u8; 32] = result.try_into().expect("result should have length 32"); U256::from_be_bytes(arr).to::<u64>() } } impl Service for CallCounterService { type Parameters = ApplicationId<EvmAbi>; async fn new(runtime: ServiceRuntime<Self>) -> Self { CallCounterService { runtime: Arc::new(runtime), } } async fn handle_query(&self, request: CallCounterRequest) -> u64 { sol! { function get_value(); function call_from_wasm(address remote_address); } match request { CallCounterRequest::Query => { let query = get_valueCall {}; let query = query.abi_encode(); self.process_query(query) } CallCounterRequest::TestCallAddress => { let remote_address = address!("0000000000000000000000000000000000002000"); let call_from_wasm = call_from_wasmCall { remote_address }; let call_from_wasm = call_from_wasm.abi_encode(); self.process_query(call_from_wasm) } CallCounterRequest::Increment(value) => { let operation = CallCounterOperation::Increment(value); self.runtime.schedule_operation(&operation); 0 } CallCounterRequest::ContractTestCallAddress => { let operation = CallCounterOperation::TestCallAddress; self.runtime.schedule_operation(&operation); 0 } } } }
rust
Apache-2.0
69f159d2106f7fc70870ce70074c55850bf1303b
2026-01-04T15:33:08.660695Z
false
linera-io/linera-protocol
https://github.com/linera-io/linera-protocol/blob/69f159d2106f7fc70870ce70074c55850bf1303b/examples/matching-engine/src/contract.rs
examples/matching-engine/src/contract.rs
// Copyright (c) Zefchain Labs, Inc. // SPDX-License-Identifier: Apache-2.0 #![cfg_attr(target_arch = "wasm32", no_main)] mod state; use linera_sdk::{ linera_base_types::{Account, AccountOwner, Amount, ChainId, WithContractAbi}, views::{linera_views, RootView, View}, Contract, ContractRuntime, }; use matching_engine::{ MatchingEngineAbi, Message, Operation, Order, OrderNature, Parameters, Price, }; use state::{MatchingEngineState, ModifyQuantity, Transfer}; pub struct MatchingEngineContract { state: MatchingEngineState, runtime: ContractRuntime<Self>, } linera_sdk::contract!(MatchingEngineContract); impl WithContractAbi for MatchingEngineContract { type Abi = MatchingEngineAbi; } impl Contract for MatchingEngineContract { type Message = Message; type InstantiationArgument = (); type Parameters = Parameters; type EventValue = (); async fn load(mut runtime: ContractRuntime<Self>) -> Self { let parameters = runtime.application_parameters(); let context = linera_views::context::ViewContext::new_unchecked( runtime.key_value_store(), Vec::new(), parameters, ); let state = MatchingEngineState::load(context) .await .expect("Failed to load state"); MatchingEngineContract { state, runtime } } async fn instantiate(&mut self, _argument: ()) {} /// Executes an order operation, or closes the chain. /// /// If the chain is the one of the matching engine then the order is processed /// locally. Otherwise, it gets transmitted as a message to the chain of the engine. async fn execute_operation(&mut self, operation: Operation) -> Self::Response { match operation { Operation::ExecuteOrder { order } => { self.runtime .application_parameters() .check_precision(&order); let owner = order.owner(); let chain_id = self.runtime.chain_id(); self.runtime .check_account_permission(owner) .expect("Permission for ExecuteOrder operation"); if chain_id == self.runtime.application_creator_chain_id() { self.execute_order_local(order, chain_id).await; } else { self.execute_order_remote(order); } } Operation::CloseChain => { let order_ids = self .state .orders .indices() .await .expect("Failed to read existing order IDs"); for order_id in order_ids { match self.state.modify_order(order_id, ModifyQuantity::All).await { Some(transfer) => self.send_to(transfer), // Orders with amount zero may have been cleared in an earlier iteration. None => continue, } } self.runtime .close_chain() .expect("The application does not have permissions to close the chain."); } } } /// Execution of the order on the creation chain async fn execute_message(&mut self, message: Message) { assert_eq!( self.runtime.chain_id(), self.runtime.application_creator_chain_id(), "Action can only be executed on the chain that created the matching engine" ); match message { Message::ExecuteOrder { order } => { let owner = order.owner(); let origin_chain_id = self.runtime.message_origin_chain_id().expect( "Incoming message origin chain ID has to be available when executing a message", ); self.runtime .check_account_permission(owner) .expect("Permission for ExecuteOrder message"); self.execute_order_local(order, origin_chain_id).await; } } } async fn store(mut self) { self.state.save().await.expect("Failed to save state"); } } impl MatchingEngineContract { /// Calls into the Fungible Token application to receive tokens from the given account. fn receive_from_account( &mut self, owner: &AccountOwner, quantity: &Amount, nature: &OrderNature, price: &Price, ) { let destination = Account { chain_id: self.runtime.chain_id(), owner: self.runtime.application_id().into(), }; let (amount, token_idx) = self .runtime .application_parameters() .get_amount_idx(nature, price, quantity); self.transfer(*owner, amount, destination, token_idx) } /// Transfers `amount` tokens from the funds in custody to the `destination`. fn send_to(&mut self, transfer: Transfer) { let destination = transfer.account; let owner_app = self.runtime.application_id().into(); self.transfer(owner_app, transfer.amount, destination, transfer.token_idx); } /// Transfers tokens from the owner to the destination fn transfer( &mut self, owner: AccountOwner, amount: Amount, target_account: Account, token_idx: u32, ) { let transfer = fungible::FungibleOperation::Transfer { owner, amount, target_account, }; let token = self.runtime.application_parameters().fungible_id(token_idx); self.runtime.call_application(true, token, &transfer); } /// Execution of orders. There are three kinds: /// * Cancel for total cancellation /// * Modify where the order is partially cancelled /// * Insertion order where an order is inserted into the system. It goes into following steps: /// - Transfer of tokens corresponding to the order in question so that it can be paid /// to the counterparty. /// - Insertion of the order into the market and immediately uncrossing the market that /// is making sure that at the end we have best bid < best ask. /// - Creation of the corresponding orders and operation of the corresponding transfers async fn execute_order_local(&mut self, order: Order, chain_id: ChainId) { match order { Order::Insert { owner, quantity, nature, price, } => { self.receive_from_account(&owner, &quantity, &nature, &price); let account = Account { chain_id, owner }; let transfers = self .state .insert_and_uncross_market(&account, quantity, nature, &price) .await; for transfer in transfers { self.send_to(transfer); } } Order::Cancel { owner, order_id } => { self.state.check_order_id(&order_id, &owner).await; let transfer = self .state .modify_order(order_id, ModifyQuantity::All) .await .expect("Order is not present therefore cannot be cancelled"); self.send_to(transfer); } Order::Modify { owner, order_id, reduce_quantity, } => { self.state.check_order_id(&order_id, &owner).await; let transfer = self .state .modify_order(order_id, ModifyQuantity::Partial(reduce_quantity)) .await .expect("Order is not present therefore cannot be cancelled"); self.send_to(transfer); } } } /// Execution of the remote order. This is done in two steps: /// * Transfer of the token (under the same owner to the chain of the matching engine) /// This is similar to the code for the crowd-funding. /// * Creation of the message that will represent the order on the chain of the matching /// engine fn execute_order_remote(&mut self, order: Order) { let chain_id = self.runtime.application_creator_chain_id(); let message = Message::ExecuteOrder { order: order.clone(), }; if let Order::Insert { owner, quantity, nature, price, } = order { // First, move the funds to the matching engine chain (under the same owner). let destination = Account { chain_id, owner }; let (amount, token_idx) = self .runtime .application_parameters() .get_amount_idx(&nature, &price, &quantity); self.transfer(owner, amount, destination, token_idx); } self.runtime .prepare_message(message) .with_authentication() .send_to(chain_id); } }
rust
Apache-2.0
69f159d2106f7fc70870ce70074c55850bf1303b
2026-01-04T15:33:08.660695Z
false
linera-io/linera-protocol
https://github.com/linera-io/linera-protocol/blob/69f159d2106f7fc70870ce70074c55850bf1303b/examples/matching-engine/src/lib.rs
examples/matching-engine/src/lib.rs
// Copyright (c) Zefchain Labs, Inc. // SPDX-License-Identifier: Apache-2.0 /*! ABI of the Matching Engine Example Application */ use async_graphql::{scalar, InputObject, Request, Response, SimpleObject}; use fungible::FungibleTokenAbi; use linera_sdk::{ graphql::GraphQLMutationRoot, linera_base_types::{AccountOwner, Amount, ApplicationId, ContractAbi, ServiceAbi}, views::{CustomSerialize, ViewError}, }; use serde::{Deserialize, Serialize}; pub struct MatchingEngineAbi; impl ContractAbi for MatchingEngineAbi { type Operation = Operation; type Response = (); } impl ServiceAbi for MatchingEngineAbi { type Query = Request; type QueryResponse = Response; } /// The asking or bidding price of token 1 in units of token 0. /// /// Forgetting about types and units, if `account` is buying `quantity` for a `price` value: /// ```ignore /// account[0] -= price * quantity * 10^-price_decimals; /// account[1] += quantity; /// ``` /// where `price_decimals` is a parameter set when the market is created. /// /// The `quantity` (also called _count_) is of type `Amount` as well as the balance of the /// accounts. Therefore, the number of decimals used by quantities in a valid order must /// not exceed `Amount::DECIMAL_PLACES - price_decimals`. /// /// When we have ask > bid then the winner for the residual cash is the liquidity provider. /// We choose to force the price to be an integer u64. This is because the tokens are undivisible. /// In practice, this means that the value of token1 has to be much higher than the price of token0 /// just as in a normal market where the price is in multiple of cents. #[derive( Clone, Copy, Debug, PartialEq, PartialOrd, Deserialize, Serialize, SimpleObject, InputObject, )] #[graphql(input_name = "PriceInput")] pub struct Price { /// A price expressed as a multiple of 10^-price_decimals increments. pub price: u64, } impl Price { pub fn to_bid(&self) -> PriceBid { PriceBid { price: self.price } } pub fn to_ask(&self) -> PriceAsk { PriceAsk { price: self.price } } } #[derive(Clone, Copy, Debug, SimpleObject, InputObject)] #[graphql(input_name = "PriceAskInput")] pub struct PriceAsk { /// A price expressed as a multiple of 10^-price_decimals increments. pub price: u64, } impl PriceAsk { pub fn to_price(&self) -> Price { Price { price: self.price } } } /// We use the custom serialization for the PriceAsk so that the order of the serialization /// corresponds to the order of the Prices. impl CustomSerialize for PriceAsk { fn to_custom_bytes(&self) -> Result<Vec<u8>, ViewError> { let mut short_key = bcs::to_bytes(&self.price)?; short_key.reverse(); Ok(short_key) } fn from_custom_bytes(short_key: &[u8]) -> Result<Self, ViewError> { let mut bytes = short_key.to_vec(); bytes.reverse(); let price = bcs::from_bytes(&bytes)?; Ok(PriceAsk { price }) } } #[derive(Clone, Copy, Debug, SimpleObject, InputObject)] #[graphql(input_name = "PriceBidInput")] pub struct PriceBid { /// A price expressed as a multiple of 10^-price_decimals increments. pub price: u64, } impl PriceBid { pub fn to_price(&self) -> Price { Price { price: self.price } } } /// We use the custom serialization for the PriceBid so that the order of the serialization /// corresponds to the order of the Prices. impl CustomSerialize for PriceBid { fn to_custom_bytes(&self) -> Result<Vec<u8>, ViewError> { let price_rev = u64::MAX - self.price; let mut short_key = bcs::to_bytes(&price_rev)?; short_key.reverse(); Ok(short_key) } fn from_custom_bytes(short_key: &[u8]) -> Result<Self, ViewError> { let mut bytes = short_key.to_vec(); bytes.reverse(); let price_rev = bcs::from_bytes::<u64>(&bytes)?; let price = u64::MAX - price_rev; Ok(PriceBid { price }) } } /// An identifier for a buy or sell order pub type OrderId = u64; #[derive(Clone, Debug, Serialize, Deserialize)] pub enum OrderNature { /// A bid for buying token 1 and paying in token 0 Bid, /// An ask for selling token 1, to be paid in token 0 Ask, } scalar!(OrderNature); #[derive(Clone, Debug, Serialize, Deserialize)] pub enum Order { /// Insertion of an order Insert { owner: AccountOwner, quantity: Amount, nature: OrderNature, price: Price, }, /// Cancelling of an order Cancel { owner: AccountOwner, order_id: OrderId, }, /// Modifying order (only decreasing is allowed) Modify { owner: AccountOwner, order_id: OrderId, reduce_quantity: Amount, }, } scalar!(Order); impl Order { /// Get the owner from the order pub fn owner(&self) -> AccountOwner { match self { Order::Insert { owner, .. } => *owner, Order::Cancel { owner, .. } => *owner, Order::Modify { owner, .. } => *owner, } } pub fn check_precision(&self, price_decimals: u16) -> Result<(), &'static str> { // Check if price_decimals is too high if price_decimals as u8 > Amount::DECIMAL_PLACES { return Err("price_decimals exceeds Amount::DECIMAL_PLACES"); } // Get the quantity/amount to check based on the order type let quantity = match self { Order::Insert { quantity, .. } => *quantity, Order::Modify { reduce_quantity, .. } => *reduce_quantity, Order::Cancel { .. } => return Ok(()), // No quantity to check }; // Calculate the minimum precision unit allowed // If price_decimals = 2, we need the amount to be divisible by 10^2 let min_unit = 10u128.pow(price_decimals as u32); // Reconstruct the full u128 value from upper and lower halves let full_value = (quantity.upper_half() as u128) << 64 | (quantity.lower_half() as u128); // Check if the quantity is divisible by the minimum unit // This ensures it doesn't use more than (DECIMAL_PLACES - price_decimals) decimal places if full_value % min_unit != 0 { return Err("Quantity has too much precision"); } Ok(()) } } /// When the matching engine is created we need to create to /// trade between two tokens 0 and 1. Those two tokens /// are put as parameters in the creation of the matching engine #[derive(Clone, Copy, Debug, Deserialize, Serialize)] pub struct Parameters { /// The token0 and token1 used for the matching engine pub tokens: [ApplicationId<FungibleTokenAbi>; 2], /// The number of decimals for the smallest increment of a price (aka "tick size"). /// This limits the number of decimals "quantities" can use in a valid order. pub price_decimals: u16, } scalar!(Parameters); impl Parameters { pub fn check_precision(&self, order: &Order) { order .check_precision(self.price_decimals) .expect("Invalid precision in order"); } pub fn product_price_amount(&self, price: Price, quantity: Amount) -> Amount { let count = quantity.saturating_div(10u128.pow(self.price_decimals as u32)); count .try_mul(price.price as u128) .expect("overflow in pricing") } /// The application engine is trading between two tokens. Those tokens are the parameters of the /// construction of the exchange and are accessed by index in the system. pub fn fungible_id(&self, token_idx: u32) -> ApplicationId<FungibleTokenAbi> { self.tokens[token_idx as usize] } /// Returns amount and type of tokens that need to be transferred to the matching engine when /// an order is added: /// * For an ask, just the token1 have to be put forward /// * For a bid, the product of the price with the amount has to be put pub fn get_amount_idx( &self, nature: &OrderNature, price: &Price, quantity: &Amount, ) -> (Amount, u32) { match nature { OrderNature::Bid => { let size0 = self.product_price_amount(*price, *quantity); (size0, 0) } OrderNature::Ask => (*quantity, 1), } } } /// Operations that can be sent to the application. #[derive(Debug, Deserialize, Serialize, GraphQLMutationRoot)] pub enum Operation { /// The order that is going to be executed on the chain of the order book. ExecuteOrder { order: Order }, /// Close this chain, and cancel all orders. /// Requires that this application is authorized to close the chain. CloseChain, } /// Messages that can be processed by the application. #[derive(Debug, Deserialize, Serialize)] pub enum Message { /// The order being transmitted from the chain and received by the chain of the order book. ExecuteOrder { order: Order }, } #[cfg(test)] mod tests { use linera_sdk::{linera_base_types::Amount, views::CustomSerialize}; use super::{Order, OrderNature, Price, PriceAsk, PriceBid}; #[test] fn test_check_precision() { use linera_sdk::linera_base_types::{AccountOwner, CryptoHash}; let owner = AccountOwner::from(CryptoHash::from([0; 32])); // Test with price_decimals = 2, max allowed precision is 18 - 2 = 16 decimals let price_decimals = 2; // Valid: quantity with 16 decimals (divisible by 10^2) let valid_order = Order::Insert { owner, quantity: Amount::from_attos(100), // 100 attotokens, divisible by 100 nature: OrderNature::Bid, price: Price { price: 1000 }, }; assert!(valid_order.check_precision(price_decimals).is_ok()); // Invalid: quantity with 18 decimals (not divisible by 10^2) let invalid_order = Order::Insert { owner, quantity: Amount::from_attos(101), // 101 attotokens, not divisible by 100 nature: OrderNature::Bid, price: Price { price: 1000 }, }; assert!(invalid_order.check_precision(price_decimals).is_err()); // Test Modify order let modify_valid = Order::Modify { owner, order_id: 1, reduce_quantity: Amount::from_attos(200), }; assert!(modify_valid.check_precision(price_decimals).is_ok()); let modify_invalid = Order::Modify { owner, order_id: 1, reduce_quantity: Amount::from_attos(199), }; assert!(modify_invalid.check_precision(price_decimals).is_err()); // Test Cancel order (should always succeed) let cancel_order = Order::Cancel { owner, order_id: 1 }; assert!(cancel_order.check_precision(price_decimals).is_ok()); // Test with price_decimals = 0 (any quantity should be valid) let order_zero_decimals = Order::Insert { owner, quantity: Amount::from_attos(1), nature: OrderNature::Ask, price: Price { price: 500 }, }; assert!(order_zero_decimals.check_precision(0).is_ok()); // Test edge case: price_decimals exceeds Amount::DECIMAL_PLACES assert!(valid_order.check_precision(19).is_err()); } #[test] fn test_ordering_serialization() { let n = 20; let mut vec = Vec::new(); let mut val = 1; for _ in 0..n { val *= 3; vec.push(val); } for i in 1..vec.len() { let val1 = vec[i - 1]; let val2 = vec[i]; assert!(val1 < val2); let price_ask1 = PriceAsk { price: val1 }; let price_ask2 = PriceAsk { price: val2 }; let price_bid1 = PriceBid { price: val1 }; let price_bid2 = PriceBid { price: val2 }; let ser_ask1 = price_ask1.to_custom_bytes().unwrap(); let ser_ask2 = price_ask2.to_custom_bytes().unwrap(); let ser_bid1 = price_bid1.to_custom_bytes().unwrap(); let ser_bid2 = price_bid2.to_custom_bytes().unwrap(); assert!(ser_ask1 < ser_ask2); assert!(ser_bid1 > ser_bid2); let price_ask1_back = PriceAsk::from_custom_bytes(&ser_ask1).unwrap(); let price_ask2_back = PriceAsk::from_custom_bytes(&ser_ask2).unwrap(); let price_bid1_back = PriceBid::from_custom_bytes(&ser_bid1).unwrap(); let price_bid2_back = PriceBid::from_custom_bytes(&ser_bid2).unwrap(); assert_eq!(price_ask1.price, price_ask1_back.price); assert_eq!(price_ask2.price, price_ask2_back.price); assert_eq!(price_bid1.price, price_bid1_back.price); assert_eq!(price_bid2.price, price_bid2_back.price); } } }
rust
Apache-2.0
69f159d2106f7fc70870ce70074c55850bf1303b
2026-01-04T15:33:08.660695Z
false
linera-io/linera-protocol
https://github.com/linera-io/linera-protocol/blob/69f159d2106f7fc70870ce70074c55850bf1303b/examples/matching-engine/src/state.rs
examples/matching-engine/src/state.rs
// Copyright (c) Zefchain Labs, Inc. // SPDX-License-Identifier: Apache-2.0 #![allow(dead_code)] use std::{cmp::min, collections::BTreeSet}; use async_graphql::SimpleObject; use linera_sdk::{ linera_base_types::{Account, AccountOwner, Amount}, views::{linera_views, linera_views::context::Context as _}, KeyValueStore, }; use linera_views::views::{RootView, View}; use matching_engine::{OrderId, OrderNature, Parameters, Price, PriceAsk, PriceBid}; use serde::{Deserialize, Serialize}; pub type Context = linera_views::context::ViewContext<Parameters, KeyValueStore>; pub type CustomCollectionView<K, V> = linera_views::collection_view::CustomCollectionView<Context, K, V>; pub type MapView<K, V> = linera_views::map_view::MapView<Context, K, V>; pub type QueueView<T> = linera_views::queue_view::QueueView<Context, T>; pub type RegisterView<T> = linera_views::register_view::RegisterView<Context, T>; /// The order entry in the order book #[derive(Clone, Debug, Deserialize, Serialize, SimpleObject)] pub struct OrderEntry { /// The number of token1 being bought or sold pub quantity: Amount, /// The one who has created the order pub account: Account, /// The order_id (needed for possible cancel or modification) pub order_id: OrderId, } /// This is the entry present in the state so that we can access /// information from the order_id. #[derive(Clone, Debug, Serialize, Deserialize, SimpleObject)] pub struct KeyBook { /// The corresponding price pub price: Price, /// The nature of the order pub nature: OrderNature, /// The owner used for checks pub account: Account, } /// The AccountInfo used for storing which order_id are owned by /// each owner. #[derive(Default, Clone, Debug, Serialize, Deserialize, SimpleObject)] pub struct AccountInfo { /// The list of orders pub orders: BTreeSet<OrderId>, } /// The price level is contained in a QueueView /// The queue starts with the oldest order to the newest. /// When an order is cancelled it is zero. But if that /// cancelled order is not the oldest, then it remains /// though with a size zero. #[derive(View, SimpleObject)] #[view(context = Context)] pub struct LevelView { pub queue: QueueView<OrderEntry>, } /// The matching engine containing the information. #[derive(RootView, SimpleObject)] #[view(context = Context)] pub struct MatchingEngineState { /// The next order_id to be used. pub next_order_id: RegisterView<OrderId>, /// The map of the outstanding bids, by the bitwise complement of /// the revert of the price. The order is from the best price /// level (highest proposed by buyer) to the worst pub bids: CustomCollectionView<PriceBid, LevelView>, /// The map of the outstanding asks, by the bitwise complement of /// the price. The order is from the best one (smallest asked price /// by seller) to the worst. pub asks: CustomCollectionView<PriceAsk, LevelView>, /// The map with the list of orders giving for each order_id the /// fundamental information on the order (price, nature, account) pub orders: MapView<OrderId, KeyBook>, /// The map giving for each account owner the set of order_id /// owned by that owner. pub account_info: MapView<AccountOwner, AccountInfo>, } impl MatchingEngineState { fn parameters(&self) -> Parameters { *self.context().extra() } /// Returns the [`LevelView`] for a specified ask `price`. pub async fn ask_level(&mut self, price: &PriceAsk) -> &mut LevelView { self.asks .load_entry_mut(price) .await .expect("Failed to load `LevelView` for an ask price") } /// Returns the [`LevelView`] for a specified bid `price`. pub async fn bid_level(&mut self, price: &PriceBid) -> &mut LevelView { self.bids .load_entry_mut(price) .await .expect("Failed to load `LevelView` for a bid price") } /// Checks that the order exists and has been issued by the claimed owner. pub async fn check_order_id(&self, order_id: &OrderId, owner: &AccountOwner) { let value = self .orders .get(order_id) .await .expect("Failed to load order"); match value { None => panic!("Order is not present therefore cannot be cancelled"), Some(value) => { assert_eq!( &value.account.owner, owner, "The owner of the order is not matching with the owner put" ); } } } /// Modifies the order from the order_id. /// This means that some transfers have to be done and the size depends /// whether ask or bid. pub async fn modify_order( &mut self, order_id: OrderId, cancel_quantity: ModifyQuantity, ) -> Option<Transfer> { let key_book = self .orders .get(&order_id) .await .expect("Failed to load order")?; let transfer = match key_book.nature { OrderNature::Bid => { let view = self.bid_level(&key_book.price.to_bid()).await; let (cancel_quantity, remove_order_id) = view.modify_order_level(order_id, cancel_quantity).await?; if remove_order_id { self.remove_order_id((key_book.account.owner, order_id)) .await; } let cancel_amount = self .parameters() .product_price_amount(key_book.price, cancel_quantity); Transfer { account: key_book.account, amount: cancel_amount, token_idx: 0, } } OrderNature::Ask => { let view = self.ask_level(&key_book.price.to_ask()).await; let (cancel_quantity, remove_order_id) = view.modify_order_level(order_id, cancel_quantity).await?; if remove_order_id { self.remove_order_id((key_book.account.owner, order_id)) .await; } Transfer { account: key_book.account, amount: cancel_quantity, token_idx: 1, } } }; Some(transfer) } /// Gets the order_id that increases starting from 0. fn get_new_order_id(&mut self) -> OrderId { let value = self.next_order_id.get_mut(); let value_ret = *value; *value += 1; value_ret } /// Inserts the order_id and insert it into: /// * account_info which give the orders by owner /// * The orders which contain the symbolic information and the key_book. async fn insert_order( &mut self, account: Account, nature: OrderNature, order_id: OrderId, price: Price, ) { let account_info = self .account_info .get_mut_or_default(&account.owner) .await .expect("Failed to load account information"); account_info.orders.insert(order_id); let key_book = KeyBook { price, nature, account, }; self.orders .insert(&order_id, key_book) .expect("Failed to insert order"); } /// Removes one single (owner, order_id) from the database /// * This is done for the info by owners /// * And the symbolic information of orders async fn remove_order_id(&mut self, entry: (AccountOwner, OrderId)) { let (owner, order_id) = entry; let account_info = self .account_info .get_mut(&owner) .await .expect("account_info") .unwrap(); account_info.orders.remove(&order_id); } /// Removes a bunch of order_id async fn remove_order_ids(&mut self, entries: Vec<(AccountOwner, OrderId)>) { for entry in entries { self.remove_order_id(entry).await; } } /// Inserts an order into the matching engine and this creates several things: /// * The price levels that matches are selected /// * Getting from the best matching price to the least good the price levels /// are cleared. /// * That clearing creates a number of transfer orders. /// * If after the level clearing the order is completely filled then it is not /// inserted. Otherwise, it became a liquidity order in the matching engine pub async fn insert_and_uncross_market( &mut self, account: &Account, quantity: Amount, nature: OrderNature, price: &Price, ) -> Vec<Transfer> { // Bids are ordered from the highest bid (most preferable) to the smallest bid. // Asks are ordered from the smallest (most preferable) to the highest. // The prices have custom serialization so that they are in increasing order. // To reverse the order of the bids, we take the bitwise complement of the price. let order_id = self.get_new_order_id(); let mut final_quantity = quantity; let mut transfers = Vec::new(); match nature { OrderNature::Bid => { let mut matching_price_asks = Vec::new(); self.asks .for_each_index_while(|price_ask| { let matches = price_ask.to_price() <= *price; if matches { matching_price_asks.push(price_ask); } Ok(matches) }) .await .expect("Failed to iterate over ask prices"); for price_ask in matching_price_asks { let view = self.ask_level(&price_ask).await; let remove_entry = view .level_clearing( account, &mut final_quantity, &mut transfers, &nature, price_ask.to_price(), *price, ) .await; if view.queue.count() == 0 { self.asks .remove_entry(&price_ask) .expect("Failed to remove ask level"); } self.remove_order_ids(remove_entry).await; if final_quantity == Amount::ZERO { break; } } if final_quantity != Amount::ZERO { let view = self.bid_level(&price.to_bid()).await; let order = OrderEntry { quantity: final_quantity, account: *account, order_id, }; view.queue.push_back(order); self.insert_order(*account, OrderNature::Bid, order_id, *price) .await; } } OrderNature::Ask => { let mut matching_price_bids = Vec::new(); self.bids .for_each_index_while(|price_bid| { let matches = price_bid.to_price() >= *price; if matches { matching_price_bids.push(price_bid); } Ok(matches) }) .await .expect("Failed to iterate over bid prices"); for price_bid in matching_price_bids { let view = self.bid_level(&price_bid).await; let remove_entry = view .level_clearing( account, &mut final_quantity, &mut transfers, &nature, price_bid.to_price(), *price, ) .await; if view.queue.count() == 0 { self.bids .remove_entry(&price_bid) .expect("Failed to remove bid level"); } self.remove_order_ids(remove_entry).await; if final_quantity == Amount::ZERO { break; } } if final_quantity != Amount::ZERO { let view = self.ask_level(&price.to_ask()).await; let order = OrderEntry { quantity: final_quantity, account: *account, order_id, }; view.queue.push_back(order); self.insert_order(*account, OrderNature::Ask, order_id, *price) .await; } } } transfers } } /// Transfer operation back to the owners #[derive(Clone)] pub struct Transfer { /// Beneficiary of the transfer pub account: Account, /// Amount being transferred pub amount: Amount, /// Index of the token being transferred (0 or 1) pub token_idx: u32, } /// An order can be cancelled which removes it totally or /// modified which is a partial cancellation. The size of the /// order can never increase. #[derive(Clone, Debug)] pub enum ModifyQuantity { All, Partial(Amount), } impl LevelView { fn parameters(&self) -> Parameters { *self.context().extra() } /// A price level is cleared starting from the oldest one till the /// new order is completely filled or there is no more liquidity /// providing order remaining to fill it. pub async fn level_clearing( &mut self, account: &Account, quantity: &mut Amount, transfers: &mut Vec<Transfer>, nature: &OrderNature, price_level: Price, price_insert: Price, ) -> Vec<(AccountOwner, OrderId)> { let parameters = self.parameters(); let mut remove_order = Vec::new(); let orders = self .queue .iter_mut() .await .expect("Failed to load iterator over orders"); for order in orders { let fill = min(order.quantity, *quantity); quantity.try_sub_assign(fill).unwrap(); order.quantity.try_sub_assign(fill).unwrap(); if fill > Amount::ZERO { transfers.extend_from_slice(&Self::get_transfers( &parameters, nature, fill, account, order, price_level, price_insert, )); } if order.quantity == Amount::ZERO { remove_order.push((order.account.owner, order.order_id)); } if *quantity == Amount::ZERO { break; } } self.remove_zero_orders_from_level().await; remove_order } /// Creates the transfers corresponding to the order: /// /// * `nature` is the nature of the order in question. /// * `fill` is the amount that is being processed. /// * `account` is the account owning the new order being inserted. /// * `order_level` is the liquidity providing order. /// * `price_level` is the price of the existing order that provides liquidity. /// * `price_insert` is the price that of the newly added order. /// /// If the new order satisfies bid > best_ask or ask < best_bid /// then there is money on the table. There are three possible /// ways to handle this: /// /// * The delta gets to the owner of the matching engine. /// * The liquidity providing order gets the delta. /// * The liquidity eating order gets the delta. /// /// We choose the second scenario since the liquidity providing /// order is waiting and so deserves to be rewarded for the wait. fn get_transfers( parameters: &Parameters, nature: &OrderNature, fill: Amount, account: &Account, order_level: &OrderEntry, price_level: Price, // the price that was present in the level price_insert: Price, // the price of the inserted order ) -> Vec<Transfer> { let mut transfers = Vec::new(); match nature { OrderNature::Bid => { // The order offers to buy token1 at price price_insert // * When the old order was created fill of token1 were committed // by the seller. // * When the new order is created price_insert * fill of token0 // were committed by the buyer. // The result is that // * price_insert * fill of token0 go to the seller (more than he expected) // * fill of token1 go to the buyer. assert!(price_insert >= price_level); let transfer_to_buyer = Transfer { account: *account, amount: fill, token_idx: 1, }; let fill0 = parameters.product_price_amount(price_insert, fill); let transfer_to_seller = Transfer { account: order_level.account, amount: fill0, token_idx: 0, }; transfers.push(transfer_to_buyer); transfers.push(transfer_to_seller); } OrderNature::Ask => { // The order offers to sell token1 at price price_insert // * When the old order was created, price_level * fill of token0 // had to be committed by the buyer. // * When the new order is created, fill of token1 have to // be committed by the seller. // The result is that // * price_insert * fill have to be sent to the seller // * the buyer receives // - fill of token1 // - (price_level - price_insert) fill of token0 (nice bonus) assert!(price_insert <= price_level); let fill0 = parameters.product_price_amount(price_insert, fill); let transfer_to_seller = Transfer { account: *account, amount: fill0, token_idx: 0, }; let transfer_to_buyer1 = Transfer { account: order_level.account, amount: fill, token_idx: 1, }; transfers.push(transfer_to_buyer1); transfers.push(transfer_to_seller); if price_level != price_insert { let price_diff = Price { price: price_level.price - price_insert.price, }; let fill0 = parameters.product_price_amount(price_diff, fill); let transfer_to_buyer0 = Transfer { account: order_level.account, amount: fill0, token_idx: 0, }; transfers.push(transfer_to_buyer0); } } } transfers } /// Orders which have length 0 should be removed from the system. /// It is possible that we have some zero orders in the QueueView /// under the condition that they are not the oldest. /// An order can be of size zero for two reasons: /// * It has been totally cancelled /// * It has been filled that is the owner got what they wanted. pub async fn remove_zero_orders_from_level(&mut self) { // If some order has amount zero but is after an order of non-zero amount, then it is left. let iter = self .queue .iter_mut() .await .expect("Failed to load iterator over level queue"); let n_remove = iter .take_while(|order| order.quantity == Amount::ZERO) .count(); for _ in 0..n_remove { self.queue.delete_front(); } } /// For a specific level of price, looks at all the orders and finds the one that /// has this specific order_id. /// When that order is found, then the cancellation is applied to it. /// Then the information is emitted for the handling of this operation. pub async fn modify_order_level( &mut self, order_id: OrderId, reduce_quantity: ModifyQuantity, ) -> Option<(Amount, bool)> { let mut iter = self .queue .iter_mut() .await .expect("Failed to load iterator over level queue"); let state_order = iter.find(|order| order.order_id == order_id)?; let new_quantity = match reduce_quantity { ModifyQuantity::All => Amount::ZERO, ModifyQuantity::Partial(reduce_quantity) => state_order .quantity .try_sub(reduce_quantity) .expect("Attempt to cancel a larger quantity than available"), }; let corr_reduce_quantity = state_order.quantity.try_sub(new_quantity).unwrap(); state_order.quantity = new_quantity; self.remove_zero_orders_from_level().await; Some((corr_reduce_quantity, new_quantity == Amount::ZERO)) } }
rust
Apache-2.0
69f159d2106f7fc70870ce70074c55850bf1303b
2026-01-04T15:33:08.660695Z
false
linera-io/linera-protocol
https://github.com/linera-io/linera-protocol/blob/69f159d2106f7fc70870ce70074c55850bf1303b/examples/matching-engine/src/service.rs
examples/matching-engine/src/service.rs
// Copyright (c) Zefchain Labs, Inc. // SPDX-License-Identifier: Apache-2.0 #![cfg_attr(target_arch = "wasm32", no_main)] mod state; use std::sync::Arc; use async_graphql::{EmptySubscription, Request, Response, Schema}; use linera_sdk::{ graphql::GraphQLMutationRoot, linera_base_types::WithServiceAbi, views::{linera_views, View}, Service, ServiceRuntime, }; use matching_engine::{Operation, Parameters}; use crate::state::MatchingEngineState; pub struct MatchingEngineService { state: Arc<MatchingEngineState>, runtime: Arc<ServiceRuntime<Self>>, } linera_sdk::service!(MatchingEngineService); impl WithServiceAbi for MatchingEngineService { type Abi = matching_engine::MatchingEngineAbi; } impl Service for MatchingEngineService { type Parameters = Parameters; async fn new(runtime: ServiceRuntime<Self>) -> Self { let parameters = runtime.application_parameters(); let context = linera_views::context::ViewContext::new_unchecked( runtime.key_value_store(), Vec::new(), parameters, ); let state = MatchingEngineState::load(context) .await .expect("Failed to load state"); MatchingEngineService { state: Arc::new(state), runtime: Arc::new(runtime), } } async fn handle_query(&self, request: Request) -> Response { let schema = Schema::build( self.state.clone(), Operation::mutation_root(self.runtime.clone()), EmptySubscription, ) .finish(); schema.execute(request).await } }
rust
Apache-2.0
69f159d2106f7fc70870ce70074c55850bf1303b
2026-01-04T15:33:08.660695Z
false
linera-io/linera-protocol
https://github.com/linera-io/linera-protocol/blob/69f159d2106f7fc70870ce70074c55850bf1303b/examples/matching-engine/tests/transaction.rs
examples/matching-engine/tests/transaction.rs
// Copyright (c) Zefchain Labs, Inc. // SPDX-License-Identifier: Apache-2.0 //! Integration tests for the Matching Engine application #![cfg(not(target_arch = "wasm32"))] use async_graphql::InputType; use linera_sdk::{ linera_base_types::{AccountOwner, Amount, ApplicationId, ApplicationPermissions}, test::{ActiveChain, QueryOutcome, TestValidator}, }; use matching_engine::{ MatchingEngineAbi, Operation, Order, OrderId, OrderNature, Parameters, Price, }; pub async fn get_orders( application_id: ApplicationId<MatchingEngineAbi>, chain: &ActiveChain, account_owner: AccountOwner, ) -> Option<Vec<OrderId>> { let query = format!( "query {{ accountInfo {{ entry(key: {}) {{ value {{ orders }} }} }} }}", account_owner.to_value() ); let QueryOutcome { response, .. } = chain.graphql_query(application_id, query).await; let orders = &response["accountInfo"]["entry"]["value"]["orders"]; let values = orders .as_array()? .iter() .map(|order| order.as_u64().unwrap()) .collect(); Some(values) } /// Test creating a matching engine, pushing some orders, canceling some and /// seeing how the transactions went. /// /// The operation is done in exactly the same way with the same amounts /// and quantities as the corresponding end to end test. /// /// We have 3 chains: /// * The chain A of User_a for tokens A /// * The chain B of User_b for tokens B /// * The admin chain of the matching engine. /// /// The following operations are done: /// * We create users and assign them their initial positions: /// * user_a with 10 tokens A. /// * user_b with 9 tokens B. /// * Then we create the following orders: /// * User_a: Offer to buy token B in exchange for token A for a price of 1 (or 2) with /// a quantity of 3 token B. /// User_a thus commits 3 * 1 + 3 * 2 = 9 token A to the matching engine chain and is /// left with 1 token A on chain A /// * User_b: Offer to sell token B in exchange for token A for a price of 2 (or 4) with /// a quantity of 4 token B /// User_b thus commits 4 + 4 = 8 token B on the matching engine chain and is left /// with 1 token B. /// * The price that is matching is 2 where a transaction can actually occur /// * Only 3 token B can be exchanged against 6 tokens A. /// * So, the order from user_b is only partially filled. /// * Then the orders are cancelled and the user get back their tokens. /// After the exchange we have /// * User_a: It has 9 - 6 = 3 token A and the newly acquired 3 token B. /// * User_b: It has 8 - 3 = 5 token B and the newly acquired 6 token A #[tokio::test] async fn single_transaction() { let (validator, module_id) = TestValidator::with_current_module::<MatchingEngineAbi, Parameters, ()>().await; let mut user_chain_a = validator.new_chain().await; let owner_a = AccountOwner::from(user_chain_a.public_key()); let mut user_chain_b = validator.new_chain().await; let owner_b = AccountOwner::from(user_chain_b.public_key()); let mut matching_chain = validator.new_chain().await; let admin_account = AccountOwner::from(matching_chain.public_key()); let fungible_module_id = user_chain_a .publish_bytecode_files_in::<fungible::FungibleTokenAbi, fungible::Parameters, fungible::InitialState>("../fungible") .await; let initial_state_a = fungible::InitialStateBuilder::default().with_account(owner_a, Amount::from_tokens(10)); let params_a = fungible::Parameters::new("A"); let token_id_a = user_chain_a .create_application( fungible_module_id, params_a, initial_state_a.build(), vec![], ) .await; let initial_state_b = fungible::InitialStateBuilder::default().with_account(owner_b, Amount::from_tokens(9)); let params_b = fungible::Parameters::new("B"); let token_id_b = user_chain_b .create_application( fungible_module_id, params_b, initial_state_b.build(), vec![], ) .await; // Check the initial starting amounts for chain a and chain b for (owner, amount) in [ (admin_account, None), (owner_a, Some(Amount::from_tokens(10))), (owner_b, None), ] { let value = fungible::query_account(token_id_a, &user_chain_a, owner).await; assert_eq!(value, amount); } for (owner, amount) in [ (admin_account, None), (owner_a, None), (owner_b, Some(Amount::from_tokens(9))), ] { let value = fungible::query_account(token_id_b, &user_chain_b, owner).await; assert_eq!(value, amount); } // Creating the matching engine chain let matching_parameter = Parameters { tokens: [token_id_a, token_id_b], price_decimals: 2, }; let matching_id = matching_chain .create_application( module_id, matching_parameter, (), vec![token_id_a.forget_abi(), token_id_b.forget_abi()], ) .await; // Creating the bid orders let mut bid_certificates = Vec::new(); for price in [100, 200] { let price = Price { price }; let order = Order::Insert { owner: owner_a, quantity: Amount::from_tokens(3), nature: OrderNature::Bid, price, }; let operation = Operation::ExecuteOrder { order }; let bid_certificate = user_chain_a .add_block(|block| { block.with_operation(matching_id, operation); }) .await; assert_eq!(bid_certificate.outgoing_message_count(), 2); bid_certificates.push(bid_certificate); } matching_chain .add_block(|block| { for certificate in &bid_certificates { block.with_messages_from(certificate); } }) .await; user_chain_a.handle_received_messages().await; user_chain_b.handle_received_messages().await; matching_chain.handle_received_messages().await; // Checking the values for token_a for (owner, amount) in [ (admin_account, None), (owner_a, Some(Amount::ONE)), (owner_b, None), ] { let value = fungible::query_account(token_id_a, &user_chain_a, owner).await; assert_eq!(value, amount); } for owner in [admin_account, owner_a, owner_b] { assert_eq!( fungible::query_account(token_id_a, &user_chain_b, owner).await, None ); assert_eq!( fungible::query_account(token_id_a, &matching_chain, owner).await, None ); } let mut ask_certificates = Vec::new(); for price in [400, 200] { let price = Price { price }; let order = Order::Insert { owner: owner_b, quantity: Amount::from_tokens(4), nature: OrderNature::Ask, price, }; let operation = Operation::ExecuteOrder { order }; let ask_certificate = user_chain_b .add_block(|block| { block.with_operation(matching_id, operation); }) .await; assert_eq!(ask_certificate.outgoing_message_count(), 2); ask_certificates.push(ask_certificate); } matching_chain .add_block(|block| { for certificate in &ask_certificates { block.with_messages_from(certificate); } }) .await; user_chain_a.handle_received_messages().await; user_chain_b.handle_received_messages().await; matching_chain.handle_received_messages().await; // Now querying the matching engine for the remaining orders let order_ids_a = get_orders(matching_id, &matching_chain, owner_a) .await .expect("order_ids_a"); assert_eq!(order_ids_a.len(), 1); let order_ids_b = get_orders(matching_id, &matching_chain, owner_b) .await .expect("order_ids_b"); assert_eq!(order_ids_b.len(), 2); // Checking the balances on chain A for (owner, amount) in [(owner_a, Some(Amount::from_tokens(1))), (owner_b, None)] { assert_eq!( fungible::query_account(token_id_a, &user_chain_a, owner).await, amount ); } // Checking the balances on chain B for (owner, amount) in [(owner_a, None), (owner_b, Some(Amount::from_tokens(1)))] { assert_eq!( fungible::query_account(token_id_b, &user_chain_b, owner).await, amount ); } // Cancel A's order. let order = Order::Cancel { owner: owner_a, order_id: order_ids_a[0], }; let operation = Operation::ExecuteOrder { order }; let order_certificate = user_chain_a .add_block(|block| { block.with_operation(matching_id, operation); }) .await; assert_eq!(order_certificate.outgoing_message_count(), 1); matching_chain .add_block(|block| { block.with_messages_from(&order_certificate); }) .await; user_chain_a.handle_received_messages().await; let permissions = ApplicationPermissions::new_single(matching_id.forget_abi()); matching_chain .add_block(|block| { block.with_change_application_permissions(permissions); }) .await; matching_chain .add_block(|block| { block.with_operation(matching_id, Operation::CloseChain); }) .await; user_chain_a.handle_received_messages().await; user_chain_b.handle_received_messages().await; // Check owner balances for (owner, user_chain, amount) in [ (owner_a, &matching_chain, None), (owner_b, &matching_chain, None), (owner_a, &user_chain_a, Some(Amount::from_tokens(4))), (owner_b, &user_chain_b, Some(Amount::from_tokens(6))), ] { assert_eq!( fungible::query_account(token_id_a, user_chain, owner).await, amount ); } for (owner, user_chain, amount) in [ (owner_a, &matching_chain, None), (owner_b, &matching_chain, None), (owner_a, &user_chain_a, Some(Amount::from_tokens(3))), (owner_b, &user_chain_b, Some(Amount::from_tokens(6))), ] { assert_eq!( fungible::query_account(token_id_b, user_chain, owner).await, amount ); } }
rust
Apache-2.0
69f159d2106f7fc70870ce70074c55850bf1303b
2026-01-04T15:33:08.660695Z
false
linera-io/linera-protocol
https://github.com/linera-io/linera-protocol/blob/69f159d2106f7fc70870ce70074c55850bf1303b/examples/non-fungible/src/contract.rs
examples/non-fungible/src/contract.rs
// Copyright (c) Zefchain Labs, Inc. // SPDX-License-Identifier: Apache-2.0 #![cfg_attr(target_arch = "wasm32", no_main)] mod state; use std::collections::BTreeSet; use linera_sdk::{ linera_base_types::{Account, AccountOwner, DataBlobHash, WithContractAbi}, views::{RootView, View}, Contract, ContractRuntime, }; use non_fungible::{Message, Nft, NonFungibleTokenAbi, Operation, TokenId}; use self::state::NonFungibleTokenState; pub struct NonFungibleTokenContract { state: NonFungibleTokenState, runtime: ContractRuntime<Self>, } linera_sdk::contract!(NonFungibleTokenContract); impl WithContractAbi for NonFungibleTokenContract { type Abi = NonFungibleTokenAbi; } impl Contract for NonFungibleTokenContract { type Message = Message; type InstantiationArgument = (); type Parameters = (); type EventValue = (); async fn load(runtime: ContractRuntime<Self>) -> Self { let state = NonFungibleTokenState::load(runtime.root_view_storage_context()) .await .expect("Failed to load state"); NonFungibleTokenContract { state, runtime } } async fn instantiate(&mut self, _state: Self::InstantiationArgument) { // Validate that the application parameters were configured correctly. self.runtime.application_parameters(); self.state.num_minted_nfts.set(0); } async fn execute_operation(&mut self, operation: Self::Operation) -> Self::Response { match operation { Operation::Mint { minter, name, blob_hash, } => { self.runtime .check_account_permission(minter) .expect("Permission for Mint operation"); self.mint(minter, name, blob_hash).await; } Operation::Transfer { source_owner, token_id, target_account, } => { self.runtime .check_account_permission(source_owner) .expect("Permission for Transfer operation"); let nft = self.get_nft(&token_id).await; assert_eq!(source_owner, nft.owner); self.transfer(nft, target_account).await; } Operation::Claim { source_account, token_id, target_account, } => { self.runtime .check_account_permission(source_account.owner) .expect("Permission for Claim operation"); if source_account.chain_id == self.runtime.chain_id() { let nft = self.get_nft(&token_id).await; assert_eq!(source_account.owner, nft.owner); self.transfer(nft, target_account).await; } else { self.remote_claim(source_account, token_id, target_account) } } } } async fn execute_message(&mut self, message: Message) { match message { Message::Transfer { mut nft, target_account, } => { let is_bouncing = self .runtime .message_is_bouncing() .expect("Message delivery status has to be available when executing a message"); if !is_bouncing { nft.owner = target_account.owner; } self.add_nft(nft).await; } Message::Claim { source_account, token_id, target_account, } => { self.runtime .check_account_permission(source_account.owner) .expect("Permission for Claim message"); let nft = self.get_nft(&token_id).await; assert_eq!(source_account.owner, nft.owner); self.transfer(nft, target_account).await; } } } async fn store(mut self) { self.state.save().await.expect("Failed to save state"); } } impl NonFungibleTokenContract { /// Transfers the specified NFT to another account. /// Authentication needs to have happened already. async fn transfer(&mut self, mut nft: Nft, target_account: Account) { self.remove_nft(&nft).await; if target_account.chain_id == self.runtime.chain_id() { nft.owner = target_account.owner; self.add_nft(nft).await; } else { let message = Message::Transfer { nft, target_account, }; self.runtime .prepare_message(message) .with_tracking() .send_to(target_account.chain_id); } } async fn get_nft(&self, token_id: &TokenId) -> Nft { self.state .nfts .get(token_id) .await .expect("Failure in retrieving NFT") .expect("NFT not found") } async fn mint(&mut self, owner: AccountOwner, name: String, blob_hash: DataBlobHash) { self.runtime.assert_data_blob_exists(blob_hash); let token_id = Nft::create_token_id( &self.runtime.chain_id(), &self.runtime.application_id().forget_abi(), &name, &owner, &blob_hash, *self.state.num_minted_nfts.get(), ) .expect("Failed to serialize NFT metadata"); self.add_nft(Nft { token_id, owner, name, minter: owner, blob_hash, }) .await; let num_minted_nfts = self.state.num_minted_nfts.get_mut(); *num_minted_nfts += 1; } fn remote_claim( &mut self, source_account: Account, token_id: TokenId, target_account: Account, ) { let message = Message::Claim { source_account, token_id, target_account, }; self.runtime .prepare_message(message) .with_authentication() .send_to(source_account.chain_id); } async fn add_nft(&mut self, nft: Nft) { let token_id = nft.token_id.clone(); let owner = nft.owner; self.state .nfts .insert(&token_id, nft) .expect("Error in insert statement"); if let Some(owned_token_ids) = self .state .owned_token_ids .get_mut(&owner) .await .expect("Error in get_mut statement") { owned_token_ids.insert(token_id); } else { let mut owned_token_ids = BTreeSet::new(); owned_token_ids.insert(token_id); self.state .owned_token_ids .insert(&owner, owned_token_ids) .expect("Error in insert statement"); } } async fn remove_nft(&mut self, nft: &Nft) { self.state .nfts .remove(&nft.token_id) .expect("Failure removing NFT"); let owned_token_ids = self .state .owned_token_ids .get_mut(&nft.owner) .await .expect("Error in get_mut statement") .expect("NFT set should be there!"); owned_token_ids.remove(&nft.token_id); } }
rust
Apache-2.0
69f159d2106f7fc70870ce70074c55850bf1303b
2026-01-04T15:33:08.660695Z
false
linera-io/linera-protocol
https://github.com/linera-io/linera-protocol/blob/69f159d2106f7fc70870ce70074c55850bf1303b/examples/non-fungible/src/lib.rs
examples/non-fungible/src/lib.rs
// Copyright (c) Zefchain Labs, Inc. // SPDX-License-Identifier: Apache-2.0 /*! ABI of the Non-Fungible Token Example Application */ use std::fmt::{Display, Formatter}; use async_graphql::{InputObject, Request, Response, SimpleObject}; use linera_sdk::{ linera_base_types::{ Account, AccountOwner, ApplicationId, ChainId, ContractAbi, DataBlobHash, ServiceAbi, }, ToBcsBytes, }; use serde::{Deserialize, Serialize}; #[derive( Debug, Serialize, Deserialize, Clone, PartialEq, Eq, Ord, PartialOrd, SimpleObject, InputObject, )] #[graphql(input_name = "TokenIdInput")] pub struct TokenId { pub id: Vec<u8>, } pub struct NonFungibleTokenAbi; impl ContractAbi for NonFungibleTokenAbi { type Operation = Operation; type Response = (); } impl ServiceAbi for NonFungibleTokenAbi { type Query = Request; type QueryResponse = Response; } /// An operation. #[derive(Debug, Deserialize, Serialize)] pub enum Operation { /// Mints a token Mint { minter: AccountOwner, name: String, blob_hash: DataBlobHash, }, /// Transfers a token from a (locally owned) account to a (possibly remote) account. Transfer { source_owner: AccountOwner, token_id: TokenId, target_account: Account, }, /// Same as `Transfer` but the source account may be remote. Depending on its /// configuration, the target chain may take time or refuse to process /// the message. Claim { source_account: Account, token_id: TokenId, target_account: Account, }, } /// A message. #[derive(Debug, Deserialize, Serialize)] pub enum Message { /// Transfers to the given `target` account, unless the message is bouncing, in which case /// we transfer back to the `source`. Transfer { nft: Nft, target_account: Account }, /// Claims from the given account and starts a transfer to the target account. Claim { source_account: Account, token_id: TokenId, target_account: Account, }, } #[derive(Debug, Serialize, Deserialize, Clone, SimpleObject, PartialEq, Eq)] #[serde(rename_all = "camelCase")] pub struct Nft { pub token_id: TokenId, pub owner: AccountOwner, pub name: String, pub minter: AccountOwner, pub blob_hash: DataBlobHash, } #[derive(Debug, Serialize, Deserialize, Clone, SimpleObject, PartialEq, Eq)] #[serde(rename_all = "camelCase")] pub struct NftOutput { pub token_id: String, pub owner: AccountOwner, pub name: String, pub minter: AccountOwner, pub payload: Vec<u8>, } impl NftOutput { pub fn new(nft: Nft, payload: Vec<u8>) -> Self { use base64::engine::{general_purpose::STANDARD_NO_PAD, Engine as _}; let token_id = STANDARD_NO_PAD.encode(nft.token_id.id); Self { token_id, owner: nft.owner, name: nft.name, minter: nft.minter, payload, } } pub fn new_with_token_id(token_id: String, nft: Nft, payload: Vec<u8>) -> Self { Self { token_id, owner: nft.owner, name: nft.name, minter: nft.minter, payload, } } } impl Display for TokenId { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { write!(f, "{:?}", self.id) } } impl Nft { pub fn create_token_id( chain_id: &ChainId, application_id: &ApplicationId, name: &String, minter: &AccountOwner, blob_hash: &DataBlobHash, num_minted_nfts: u64, ) -> Result<TokenId, bcs::Error> { use sha3::Digest as _; let mut hasher = sha3::Sha3_256::new(); hasher.update(chain_id.to_bcs_bytes()?); hasher.update(application_id.to_bcs_bytes()?); hasher.update(name); hasher.update(name.len().to_bcs_bytes()?); hasher.update(minter.to_bcs_bytes()?); hasher.update(blob_hash.to_bcs_bytes()?); hasher.update(num_minted_nfts.to_bcs_bytes()?); Ok(TokenId { id: hasher.finalize().to_vec(), }) } }
rust
Apache-2.0
69f159d2106f7fc70870ce70074c55850bf1303b
2026-01-04T15:33:08.660695Z
false
linera-io/linera-protocol
https://github.com/linera-io/linera-protocol/blob/69f159d2106f7fc70870ce70074c55850bf1303b/examples/non-fungible/src/state.rs
examples/non-fungible/src/state.rs
// Copyright (c) Zefchain Labs, Inc. // SPDX-License-Identifier: Apache-2.0 use std::collections::BTreeSet; use async_graphql::SimpleObject; use linera_sdk::{ linera_base_types::AccountOwner, views::{linera_views, MapView, RegisterView, RootView, ViewStorageContext}, }; use non_fungible::{Nft, TokenId}; /// The application state. #[derive(RootView, SimpleObject)] #[view(context = ViewStorageContext)] pub struct NonFungibleTokenState { // Map from token ID to the NFT data pub nfts: MapView<TokenId, Nft>, // Map from owners to the set of NFT token IDs they own pub owned_token_ids: MapView<AccountOwner, BTreeSet<TokenId>>, // Counter of NFTs minted in this chain, used for hash uniqueness pub num_minted_nfts: RegisterView<u64>, }
rust
Apache-2.0
69f159d2106f7fc70870ce70074c55850bf1303b
2026-01-04T15:33:08.660695Z
false
linera-io/linera-protocol
https://github.com/linera-io/linera-protocol/blob/69f159d2106f7fc70870ce70074c55850bf1303b/examples/non-fungible/src/service.rs
examples/non-fungible/src/service.rs
// Copyright (c) Zefchain Labs, Inc. // SPDX-License-Identifier: Apache-2.0 #![cfg_attr(target_arch = "wasm32", no_main)] mod state; use std::{ collections::{BTreeMap, BTreeSet}, sync::Arc, }; use async_graphql::{EmptySubscription, Object, Request, Response, Schema}; use base64::engine::{general_purpose::STANDARD_NO_PAD, Engine as _}; use linera_sdk::{ linera_base_types::{Account, AccountOwner, DataBlobHash, WithServiceAbi}, views::View, Service, ServiceRuntime, }; use non_fungible::{NftOutput, Operation, TokenId}; use self::state::NonFungibleTokenState; pub struct NonFungibleTokenService { state: Arc<NonFungibleTokenState>, runtime: Arc<ServiceRuntime<Self>>, } linera_sdk::service!(NonFungibleTokenService); impl WithServiceAbi for NonFungibleTokenService { type Abi = non_fungible::NonFungibleTokenAbi; } impl Service for NonFungibleTokenService { type Parameters = (); async fn new(runtime: ServiceRuntime<Self>) -> Self { let state = NonFungibleTokenState::load(runtime.root_view_storage_context()) .await .expect("Failed to load state"); NonFungibleTokenService { state: Arc::new(state), runtime: Arc::new(runtime), } } async fn handle_query(&self, request: Request) -> Response { let schema = Schema::build( QueryRoot { non_fungible_token: self.state.clone(), runtime: self.runtime.clone(), }, MutationRoot { runtime: self.runtime.clone(), }, EmptySubscription, ) .finish(); schema.execute(request).await } } struct QueryRoot { non_fungible_token: Arc<NonFungibleTokenState>, runtime: Arc<ServiceRuntime<NonFungibleTokenService>>, } #[Object] impl QueryRoot { async fn nft(&self, token_id: String) -> Option<NftOutput> { let token_id_vec = STANDARD_NO_PAD.decode(&token_id).unwrap(); let nft = self .non_fungible_token .nfts .get(&TokenId { id: token_id_vec }) .await .unwrap(); if let Some(nft) = nft { let payload = self.runtime.read_data_blob(nft.blob_hash); let nft_output = NftOutput::new_with_token_id(token_id, nft, payload); Some(nft_output) } else { None } } async fn nfts(&self) -> BTreeMap<String, NftOutput> { let mut nfts = BTreeMap::new(); self.non_fungible_token .nfts .for_each_index_value(|_token_id, nft| { let nft = nft.into_owned(); let payload = self.runtime.read_data_blob(nft.blob_hash); let nft_output = NftOutput::new(nft, payload); nfts.insert(nft_output.token_id.clone(), nft_output); Ok(()) }) .await .unwrap(); nfts } async fn owned_token_ids_by_owner(&self, owner: AccountOwner) -> BTreeSet<String> { self.non_fungible_token .owned_token_ids .get(&owner) .await .unwrap() .into_iter() .flatten() .map(|token_id| STANDARD_NO_PAD.encode(token_id.id)) .collect() } async fn owned_token_ids(&self) -> BTreeMap<AccountOwner, BTreeSet<String>> { let mut owners = BTreeMap::new(); self.non_fungible_token .owned_token_ids .for_each_index_value(|owner, token_ids| { let token_ids = token_ids.into_owned(); let new_token_ids = token_ids .into_iter() .map(|token_id| STANDARD_NO_PAD.encode(token_id.id)) .collect(); owners.insert(owner, new_token_ids); Ok(()) }) .await .unwrap(); owners } async fn owned_nfts(&self, owner: AccountOwner) -> BTreeMap<String, NftOutput> { let mut result = BTreeMap::new(); let owned_token_ids = self .non_fungible_token .owned_token_ids .get(&owner) .await .unwrap(); for token_id in owned_token_ids.into_iter().flatten() { let nft = self .non_fungible_token .nfts .get(&token_id) .await .unwrap() .unwrap(); let payload = self.runtime.read_data_blob(nft.blob_hash); let nft_output = NftOutput::new(nft, payload); result.insert(nft_output.token_id.clone(), nft_output); } result } } struct MutationRoot { runtime: Arc<ServiceRuntime<NonFungibleTokenService>>, } #[Object] impl MutationRoot { async fn mint(&self, minter: AccountOwner, name: String, blob_hash: DataBlobHash) -> [u8; 0] { let operation = Operation::Mint { minter, name, blob_hash, }; self.runtime.schedule_operation(&operation); [] } async fn transfer( &self, source_owner: AccountOwner, token_id: String, target_account: Account, ) -> [u8; 0] { let operation = Operation::Transfer { source_owner, token_id: TokenId { id: STANDARD_NO_PAD.decode(token_id).unwrap(), }, target_account, }; self.runtime.schedule_operation(&operation); [] } async fn claim( &self, source_account: Account, token_id: String, target_account: Account, ) -> [u8; 0] { let operation = Operation::Claim { source_account, token_id: TokenId { id: STANDARD_NO_PAD.decode(token_id).unwrap(), }, target_account, }; self.runtime.schedule_operation(&operation); [] } }
rust
Apache-2.0
69f159d2106f7fc70870ce70074c55850bf1303b
2026-01-04T15:33:08.660695Z
false
linera-io/linera-protocol
https://github.com/linera-io/linera-protocol/blob/69f159d2106f7fc70870ce70074c55850bf1303b/linera-persistent/build.rs
linera-persistent/build.rs
// Copyright (c) Zefchain Labs, Inc. // SPDX-License-Identifier: Apache-2.0 fn main() { cfg_aliases::cfg_aliases! { web: { all(target_arch = "wasm32", feature = "web") }, with_indexed_db: { all(web, feature = "indexed-db") }, }; }
rust
Apache-2.0
69f159d2106f7fc70870ce70074c55850bf1303b
2026-01-04T15:33:08.660695Z
false
linera-io/linera-protocol
https://github.com/linera-io/linera-protocol/blob/69f159d2106f7fc70870ce70074c55850bf1303b/linera-persistent/src/lib.rs
linera-persistent/src/lib.rs
// Copyright (c) Zefchain Labs, Inc. // SPDX-License-Identifier: Apache-2.0 /*! This crate handles persisting data types to disk with a variety of backends. */ #![allow(async_fn_in_trait)] cfg_if::cfg_if! { if #[cfg(with_indexed_db)] { pub mod indexed_db; pub use indexed_db::IndexedDb; } } cfg_if::cfg_if! { if #[cfg(feature = "fs")] { pub mod file; pub use file::File; } } pub mod memory; use std::ops::Deref; pub use memory::Memory; /// The `Persist` trait provides a wrapper around a value that can be saved in a /// persistent way. A minimal implementation provides an `Error` type, a `persist` /// function to persist the value, and an `as_mut` function to get a mutable reference to /// the value in memory. #[cfg_attr(not(web), trait_variant::make(Send))] pub trait Persist: Deref { type Error: std::error::Error + Send + Sync + 'static; /// Gets a mutable reference to the value. This is not expressed as a /// [`DerefMut`](std::ops::DerefMut) bound because it is discouraged to use this /// function! Instead, use `mutate`. fn as_mut(&mut self) -> &mut Self::Target; /// Saves the value to persistent storage. async fn persist(&mut self) -> Result<(), Self::Error>; /// Takes the value out. fn into_value(self) -> Self::Target where Self::Target: Sized; } pub trait PersistExt: Persist { /// Applies a mutation to the value, persisting when done. async fn mutate<R>( &mut self, mutation: impl FnOnce(&mut Self::Target) -> R, ) -> Result<R, Self::Error>; } impl<T: Persist> PersistExt for T { async fn mutate<R>( &mut self, mutation: impl FnOnce(&mut Self::Target) -> R, ) -> Result<R, Self::Error> { let output = mutation(self.as_mut()); self.persist().await?; Ok(output) } }
rust
Apache-2.0
69f159d2106f7fc70870ce70074c55850bf1303b
2026-01-04T15:33:08.660695Z
false
linera-io/linera-protocol
https://github.com/linera-io/linera-protocol/blob/69f159d2106f7fc70870ce70074c55850bf1303b/linera-persistent/src/memory.rs
linera-persistent/src/memory.rs
// Copyright (c) Zefchain Labs, Inc. // SPDX-License-Identifier: Apache-2.0 use super::Persist; pub type Error = std::convert::Infallible; /// A dummy [`Persist`] implementation that doesn't persist anything, but holds the value /// in memory. #[derive(Default, derive_more::Deref)] pub struct Memory<T> { #[deref] value: T, } impl<T> Memory<T> { pub fn new(value: T) -> Self { Self { value } } } impl<T: Send> Persist for Memory<T> { type Error = Error; fn as_mut(&mut self) -> &mut T { &mut self.value } fn into_value(self) -> T { self.value } async fn persist(&mut self) -> Result<(), Error> { Ok(()) } }
rust
Apache-2.0
69f159d2106f7fc70870ce70074c55850bf1303b
2026-01-04T15:33:08.660695Z
false
linera-io/linera-protocol
https://github.com/linera-io/linera-protocol/blob/69f159d2106f7fc70870ce70074c55850bf1303b/linera-persistent/src/file.rs
linera-persistent/src/file.rs
// Copyright (c) Zefchain Labs, Inc. // SPDX-License-Identifier: Apache-2.0 use std::{ io::{self, BufRead as _, Write as _}, path::Path, }; use fs4::FileExt; use thiserror_context::Context; use super::Persist; /// A guard that keeps an exclusive lock on a file. struct Lock(fs_err::File); #[derive(Debug, thiserror::Error)] enum ErrorInner { #[error("I/O error: {0}")] IoError(#[from] std::io::Error), #[error("JSON error: {0}")] JsonError(#[from] serde_json::Error), } thiserror_context::impl_context!(Error(ErrorInner)); /// Utility: run a fallible cleanup function if an operation failed, attaching the /// original operation as context to its error. trait CleanupExt { type Ok; type Error; fn or_cleanup<E>(self, f: impl FnOnce() -> Result<(), E>) -> Result<Self::Ok, Self::Error> where E: Into<Self::Error>, Result<(), E>: Context<Self::Error, Self::Ok, E>; } impl<T, W> CleanupExt for Result<T, W> where W: std::fmt::Display + Send + Sync + 'static, { type Ok = T; type Error = W; fn or_cleanup<E>(self, cleanup: impl FnOnce() -> Result<(), E>) -> Self where E: Into<W>, Result<(), E>: Context<W, T, E>, { self.or_else(|error| { if let Err(cleanup_error) = cleanup() { Err(cleanup_error).context(error) } else { Err(error) } }) } } impl Lock { /// Acquires an exclusive lock on a provided `file`, returning a [`Lock`] which will /// release the lock when dropped. pub fn new(file: fs_err::File) -> std::io::Result<Self> { file.file().try_lock_exclusive()?; Ok(Lock(file)) } } impl Drop for Lock { fn drop(&mut self) { if let Err(error) = FileExt::unlock(self.0.file()) { tracing::warn!("Failed to unlock wallet file: {error}"); } } } /// An implementation of [`Persist`] based on an atomically-updated file at a given path. /// An exclusive lock is taken using `flock(2)` to ensure that concurrent updates cannot /// happen, and writes are saved to a staging file before being moved over the old file, /// an operation that is atomic on all Unixes. pub struct File<T> { _lock: Lock, path: std::path::PathBuf, value: T, } impl<T> std::ops::Deref for File<T> { type Target = T; fn deref(&self) -> &T { &self.value } } impl<T> std::ops::DerefMut for File<T> { fn deref_mut(&mut self) -> &mut T { &mut self.value } } /// Returns options for opening and writing to the file, creating it if it doesn't /// exist. On Unix, this restricts read and write permissions to the current user. // TODO(#1924): Implement better key management. // BUG(#2053): Use a separate lock file per staging file. fn open_options() -> fs_err::OpenOptions { let mut options = fs_err::OpenOptions::new(); #[cfg(target_family = "unix")] fs_err::os::unix::fs::OpenOptionsExt::mode(&mut options, 0o600); options.create(true).read(true).write(true); options } impl<T: serde::Serialize + serde::de::DeserializeOwned> File<T> { /// Creates a new persistent file at `path` containing `value`. pub fn new(path: &Path, value: T) -> Result<Self, Error> { let this = Self { _lock: Lock::new( fs_err::OpenOptions::new() .read(true) .write(true) .create(true) .open(path)?, ) .with_context(|| format!("locking path {}", path.display()))?, path: path.into(), value, }; this.save()?; Ok(this) } /// Reads the value from a file at `path`, returning an error if it does not exist. pub fn read(path: &Path) -> Result<Self, Error> { Self::read_or_create(path, || { Err(std::io::Error::new( std::io::ErrorKind::NotFound, format!("file is empty or does not exist: {}", path.display()), ) .into()) }) } /// Reads the value from a file at `path`, calling the `value` function to create it /// if it does not exist. If it does exist, `value` will not be called. pub fn read_or_create( path: &Path, value: impl FnOnce() -> Result<T, Error>, ) -> Result<Self, Error> { let lock = Lock::new(open_options().read(true).open(path)?)?; let mut reader = io::BufReader::new(&lock.0); let file_is_empty = reader.fill_buf()?.is_empty(); let me = Self { value: if file_is_empty { value()? } else { serde_json::from_reader(reader)? }, path: path.into(), _lock: lock, }; me.save()?; Ok(me) } pub fn save(&self) -> Result<(), Error> { let mut temp_file_path = self.path.clone(); temp_file_path.set_extension("json.new"); let temp_file = open_options().open(&temp_file_path)?; let mut temp_file_writer = std::io::BufWriter::new(temp_file); let remove_temp_file = || fs_err::remove_file(&temp_file_path); serde_json::to_writer_pretty(&mut temp_file_writer, &self.value) .map_err(Error::from) .or_cleanup(remove_temp_file)?; temp_file_writer .flush() .map_err(Error::from) .or_cleanup(remove_temp_file)?; drop(temp_file_writer); fs_err::rename(&temp_file_path, &self.path)?; Ok(()) } } impl<T: serde::Serialize + serde::de::DeserializeOwned + Send> Persist for File<T> { type Error = Error; fn as_mut(&mut self) -> &mut T { &mut self.value } /// Writes the value to disk. /// /// The contents of the file need to be over-written completely, so /// a temporary file is created as a backup in case a crash occurs while /// writing to disk. /// /// The temporary file is then renamed to the original filename. If /// serialization or writing to disk fails, the temporary file is /// deleted. fn persist(&mut self) -> impl std::future::Future<Output = Result<(), Error>> { let result = self.save(); async { result } } /// Takes the value out, releasing the lock on the persistent file. fn into_value(self) -> T { self.value } }
rust
Apache-2.0
69f159d2106f7fc70870ce70074c55850bf1303b
2026-01-04T15:33:08.660695Z
false
linera-io/linera-protocol
https://github.com/linera-io/linera-protocol/blob/69f159d2106f7fc70870ce70074c55850bf1303b/linera-persistent/src/dirty.rs
linera-persistent/src/dirty.rs
// Copyright (c) Zefchain Labs, Inc. // SPDX-License-Identifier: Apache-2.0 #[derive(Clone, Debug, Default, PartialEq, Eq, derive_more::Deref, derive_more::DerefMut)] pub struct Dirty( #[deref] #[deref_mut] bool, ); impl Dirty { pub fn new(dirty: bool) -> Self { Self(dirty) } } impl Drop for Dirty { fn drop(&mut self) { if self.0 { tracing::error!("object dropped while dirty"); } } }
rust
Apache-2.0
69f159d2106f7fc70870ce70074c55850bf1303b
2026-01-04T15:33:08.660695Z
false
linera-io/linera-protocol
https://github.com/linera-io/linera-protocol/blob/69f159d2106f7fc70870ce70074c55850bf1303b/linera-persistent/src/indexed_db.rs
linera-persistent/src/indexed_db.rs
// Copyright (c) Zefchain Labs, Inc. // SPDX-License-Identifier: Apache-2.0 use indexed_db_futures::prelude::*; use tracing::instrument; use wasm_bindgen::JsValue; use wasm_bindgen_futures::wasm_bindgen; use web_sys::DomException; use super::{dirty::Dirty, Persist}; /// An implementation of [`Persist`] based on an IndexedDB record with a given key. #[derive(derive_more::Deref)] pub struct IndexedDb<T> { key: String, #[deref] value: T, database: IdbDatabase, dirty: Dirty, } impl<T: serde::Serialize> std::fmt::Debug for IndexedDb<T> { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { f.debug_struct("persistent::IndexedDb") .field("key", &self.key) .field("value", &serde_json::to_string(&self.value)) .field("dirty", &*self.dirty) .finish_non_exhaustive() } } const DATABASE_NAME: &str = "linera-client"; const STORE_NAME: &str = "linera-wallet"; #[derive(Debug, thiserror::Error)] pub enum Error { #[error("marshalling error: {0}")] Marshalling(#[source] gloo_utils::errors::JsError), #[error("DOM exception: {0:?}")] DomException(#[source] gloo_utils::errors::JsError), } impl From<serde_wasm_bindgen::Error> for Error { fn from(e: serde_wasm_bindgen::Error) -> Self { Self::Marshalling(JsValue::from(e).try_into().unwrap()) } } impl From<DomException> for Error { fn from(e: DomException) -> Self { Self::DomException(JsValue::from(e).try_into().unwrap()) } } async fn open_database() -> Result<IdbDatabase, Error> { let mut db_req = IdbDatabase::open_u32(DATABASE_NAME, 1)?; db_req.set_on_upgrade_needed(Some(|evt: &IdbVersionChangeEvent| -> Result<(), JsValue> { if !evt.db().object_store_names().any(|n| n == STORE_NAME) { evt.db().create_object_store(STORE_NAME)?; } Ok(()) })); Ok(db_req.await?) } impl<T> IndexedDb<T> { #[instrument(level = "trace", skip(value))] pub async fn new(key: &str, value: T) -> Result<Self, Error> { Ok(Self { key: key.to_owned(), value, database: open_database().await?, dirty: Dirty::new(true), }) } } impl<T: serde::de::DeserializeOwned> IndexedDb<T> { #[instrument(level = "trace")] pub async fn read(key: &str) -> Result<Option<Self>, Error> { let database = open_database().await?; let tx = database.transaction_on_one_with_mode(STORE_NAME, IdbTransactionMode::Readwrite)?; let store: IdbObjectStore = tx.object_store(STORE_NAME)?; let Some(value) = store.get_owned(key)?.await? else { return Ok(None); }; drop(tx); Ok(Some(Self { key: key.to_owned(), value: serde_wasm_bindgen::from_value(value)?, database, dirty: Dirty::new(false), })) } #[instrument(level = "trace", fields(value = &serde_json::to_string(&value).unwrap()))] pub async fn read_or_create(key: &str, value: T) -> Result<Self, Error> where T: serde::Serialize, { Ok(if let Some(this) = Self::read(key).await? { this } else { let mut this = Self::new(key, value).await?; this.persist().await?; this }) } } impl<T: serde::Serialize> Persist for IndexedDb<T> { type Error = Error; #[instrument(level = "trace")] fn as_mut(&mut self) -> &mut T { *self.dirty = true; &mut self.value } fn into_value(self) -> T { self.value } #[instrument(level = "trace")] async fn persist(&mut self) -> Result<(), Error> { let serializer = serde_wasm_bindgen::Serializer::new().serialize_large_number_types_as_bigints(true); self.database .transaction_on_one_with_mode(STORE_NAME, IdbTransactionMode::Readwrite)? .object_store(STORE_NAME)? .put_key_val_owned(&self.key, &self.value.serialize(&serializer)?)? .await?; *self.dirty = false; Ok(()) } }
rust
Apache-2.0
69f159d2106f7fc70870ce70074c55850bf1303b
2026-01-04T15:33:08.660695Z
false
linera-io/linera-protocol
https://github.com/linera-io/linera-protocol/blob/69f159d2106f7fc70870ce70074c55850bf1303b/linera-sdk-derive/src/lib.rs
linera-sdk-derive/src/lib.rs
// Copyright (c) Zefchain Labs, Inc. // SPDX-License-Identifier: Apache-2.0 //! The procedural macros for the crate `linera-sdk`. mod utils; use proc_macro::TokenStream; use proc_macro2::{Ident, Span}; use syn::{ parse_macro_input, Fields, ItemEnum, __private::{quote::quote, TokenStream2}, }; use crate::utils::{concat, snakify}; #[proc_macro_derive(GraphQLMutationRoot)] pub fn derive_mutation_root(input: TokenStream) -> TokenStream { let input = parse_macro_input!(input as ItemEnum); generate_mutation_root_code(input, "linera_sdk").into() } #[proc_macro_derive(GraphQLMutationRootInCrate)] pub fn derive_mutation_root_in_crate(input: TokenStream) -> TokenStream { let input = parse_macro_input!(input as ItemEnum); generate_mutation_root_code(input, "crate").into() } fn generate_mutation_root_code(input: ItemEnum, crate_root: &str) -> TokenStream2 { let crate_root = Ident::new(crate_root, Span::call_site()); let enum_name = input.ident; let mutation_root_name = concat(&enum_name, "MutationRoot"); let mut methods = vec![]; for variant in input.variants { let variant_name = &variant.ident; let function_name = snakify(variant_name); match variant.fields { Fields::Named(named) => { let mut fields = vec![]; let mut field_names = vec![]; for field in named.named { let name = field.ident.expect("named fields always have names"); let ty = field.ty; fields.push(quote! {#name: #ty}); field_names.push(name); } methods.push(quote! { async fn #function_name(&self, #(#fields,)*) -> [u8; 0] { let operation = #enum_name::#variant_name { #(#field_names,)* }; self.runtime.schedule_operation(&operation); [] } }); } Fields::Unnamed(unnamed) => { let mut fields = vec![]; let mut field_names = vec![]; for (i, field) in unnamed.unnamed.iter().enumerate() { let name = concat(&syn::parse_str::<Ident>("field").unwrap(), &i.to_string()); let ty = &field.ty; fields.push(quote! {#name: #ty}); field_names.push(name); } methods.push(quote! { async fn #function_name(&self, #(#fields,)*) -> [u8; 0] { let operation = #enum_name::#variant_name( #(#field_names,)* ); self.runtime.schedule_operation(&operation); [] } }); } Fields::Unit => { methods.push(quote! { async fn #function_name(&self) -> [u8; 0] { let operation = #enum_name::#variant_name; self.runtime.schedule_operation(&operation); [] } }); } }; } quote! { /// Mutation root pub struct #mutation_root_name<Application> where Application: #crate_root::Service, #crate_root::ServiceRuntime<Application>: Send + Sync, { runtime: ::std::sync::Arc<#crate_root::ServiceRuntime<Application>>, } #[async_graphql::Object] impl<Application> #mutation_root_name<Application> where Application: #crate_root::Service, #crate_root::ServiceRuntime<Application>: Send + Sync, { #(#methods)* } impl<Application> #crate_root::graphql::GraphQLMutationRoot<Application> for #enum_name where Application: #crate_root::Service, #crate_root::ServiceRuntime<Application>: Send + Sync, { type MutationRoot = #mutation_root_name<Application>; fn mutation_root( runtime: ::std::sync::Arc<#crate_root::ServiceRuntime<Application>>, ) -> Self::MutationRoot { #mutation_root_name { runtime } } } } } #[cfg(test)] pub mod tests { use syn::{parse_quote, ItemEnum, __private::quote::quote}; use crate::generate_mutation_root_code; fn assert_eq_no_whitespace(mut actual: String, mut expected: String) { // Intentionally left here for debugging purposes println!("{}", actual); actual.retain(|c| !c.is_whitespace()); expected.retain(|c| !c.is_whitespace()); assert_eq!(actual, expected); } #[test] fn test_derive_mutation_root() { let operation: ItemEnum = parse_quote! { enum SomeOperation { TupleVariant(String), StructVariant { a: u32, b: u64 }, EmptyVariant } }; let output = generate_mutation_root_code(operation, "linera_sdk"); let expected = quote! { /// Mutation root pub struct SomeOperationMutationRoot<Application> where Application: linera_sdk::Service, linera_sdk::ServiceRuntime<Application>: Send + Sync, { runtime: ::std::sync::Arc<linera_sdk::ServiceRuntime<Application>>, } #[async_graphql::Object] impl<Application> SomeOperationMutationRoot<Application> where Application: linera_sdk::Service, linera_sdk::ServiceRuntime<Application>: Send + Sync, { async fn tuple_variant(&self, field0: String,) -> [u8; 0] { let operation = SomeOperation::TupleVariant(field0,); self.runtime.schedule_operation(&operation); [] } async fn struct_variant(&self, a: u32, b: u64,) -> [u8; 0] { let operation = SomeOperation::StructVariant { a, b, }; self.runtime.schedule_operation(&operation); [] } async fn empty_variant(&self) -> [u8; 0] { let operation = SomeOperation::EmptyVariant; self.runtime.schedule_operation(&operation); [] } } impl<Application> linera_sdk::graphql::GraphQLMutationRoot<Application> for SomeOperation where Application: linera_sdk::Service, linera_sdk::ServiceRuntime<Application>: Send + Sync, { type MutationRoot = SomeOperationMutationRoot<Application>; fn mutation_root( runtime: ::std::sync::Arc<linera_sdk::ServiceRuntime<Application>>, ) -> Self::MutationRoot { SomeOperationMutationRoot { runtime } } } }; assert_eq_no_whitespace(output.to_string(), expected.to_string()); } }
rust
Apache-2.0
69f159d2106f7fc70870ce70074c55850bf1303b
2026-01-04T15:33:08.660695Z
false
linera-io/linera-protocol
https://github.com/linera-io/linera-protocol/blob/69f159d2106f7fc70870ce70074c55850bf1303b/linera-sdk-derive/src/utils.rs
linera-sdk-derive/src/utils.rs
// Copyright (c) Zefchain Labs, Inc. // SPDX-License-Identifier: Apache-2.0 use convert_case::{Case, Casing}; use proc_macro2::{Ident, Span}; /// Extracts the first `Ident` in a type and convert to snake case. pub fn snakify(ident: &Ident) -> Ident { transform_non_keyword_ident(ident, |s: String| s.to_case(Case::Snake)) } /// Extends an identifier with a suffix. pub fn concat(ident: &Ident, suffix: &str) -> Ident { transform_non_keyword_ident(ident, |s: String| format!("{}{}", s, suffix)) } /// Applies a string transformation (`transform`) to the input `Ident`. /// However, it will not apply the transform to Rust keywords. fn transform_non_keyword_ident<Transform>(ident: &Ident, transform: Transform) -> Ident where Transform: FnOnce(String) -> String, { let is_keyword = syn::parse_str::<Ident>(&ident.to_string()).is_err(); if is_keyword { ident.clone() } else { Ident::new(&transform(ident.to_string()), Span::call_site()) } }
rust
Apache-2.0
69f159d2106f7fc70870ce70074c55850bf1303b
2026-01-04T15:33:08.660695Z
false
linera-io/linera-protocol
https://github.com/linera-io/linera-protocol/blob/69f159d2106f7fc70870ce70074c55850bf1303b/linera-faucet/server/build.rs
linera-faucet/server/build.rs
// Copyright (c) Zefchain Labs, Inc. // SPDX-License-Identifier: Apache-2.0 fn main() { cfg_aliases::cfg_aliases! { with_metrics: { all(not(target_arch = "wasm32"), feature = "metrics") }, }; }
rust
Apache-2.0
69f159d2106f7fc70870ce70074c55850bf1303b
2026-01-04T15:33:08.660695Z
false
linera-io/linera-protocol
https://github.com/linera-io/linera-protocol/blob/69f159d2106f7fc70870ce70074c55850bf1303b/linera-faucet/server/src/lib.rs
linera-faucet/server/src/lib.rs
// Copyright (c) Zefchain Labs, Inc. // SPDX-License-Identifier: Apache-2.0 #![recursion_limit = "256"] //! The server component of the Linera faucet. mod database; use std::{collections::VecDeque, future::IntoFuture, net::SocketAddr, path::PathBuf, sync::Arc}; use anyhow::Context as _; use async_graphql::{EmptySubscription, Error, Schema, SimpleObject}; use async_graphql_axum::{GraphQLRequest, GraphQLResponse, GraphQLSubscription}; use axum::{Extension, Router}; use futures::{lock::Mutex, FutureExt as _}; use linera_base::{ bcs, crypto::{CryptoHash, ValidatorPublicKey}, data_types::{Amount, ApplicationPermissions, ChainDescription, Timestamp}, identifiers::{AccountOwner, BlobId, BlobType, ChainId}, ownership::ChainOwnership, }; use linera_chain::{types::ConfirmedBlockCertificate, ChainError, ChainExecutionContext}; use linera_client::{ chain_listener::{ChainListener, ChainListenerConfig, ClientContext}, config::GenesisConfig, }; use linera_core::{ client::chain_client::{self, ChainClient}, data_types::ClientOutcome, worker::WorkerError, LocalNodeError, }; use linera_execution::{ system::{OpenChainConfig, SystemOperation}, Committee, ExecutionError, Operation, }; #[cfg(feature = "metrics")] use linera_metrics::monitoring_server; use linera_storage::{Clock as _, Storage}; use serde::Deserialize; use tokio::sync::{oneshot, Notify}; use tokio_util::sync::CancellationToken; use tower_http::cors::CorsLayer; use tracing::info; use crate::database::FaucetDatabase; // Prometheus metrics for the faucet #[cfg(with_metrics)] mod metrics { use std::sync::LazyLock; use linera_base::prometheus_util::{ exponential_bucket_interval, register_histogram_vec, register_int_counter_vec, register_int_gauge_vec, }; use prometheus::{HistogramVec, IntCounterVec, IntGaugeVec}; pub static CLAIM_REQUESTS_TOTAL: LazyLock<IntCounterVec> = LazyLock::new(|| { register_int_counter_vec( "faucet_claim_requests_total", "Total number of claim requests by result", &["result"], ) }); pub static CLAIM_LATENCY: LazyLock<HistogramVec> = LazyLock::new(|| { register_histogram_vec( "faucet_claim_latency_ms", "End-to-end latency of claim requests in milliseconds", &["result"], exponential_bucket_interval(0.5, 8000.0), ) }); pub static CHAINS_CREATED_TOTAL: LazyLock<IntCounterVec> = LazyLock::new(|| { register_int_counter_vec( "faucet_chains_created_total", "Total number of chains created by the faucet", &[], ) }); pub static BATCH_SIZE: LazyLock<HistogramVec> = LazyLock::new(|| { register_histogram_vec( "faucet_batch_size", "Number of chain creation requests per batch", &[], Some(vec![1.0, 2.0, 5.0, 10.0, 20.0, 50.0, 100.0]), ) }); pub static BATCH_PROCESSING_LATENCY: LazyLock<HistogramVec> = LazyLock::new(|| { register_histogram_vec( "faucet_batch_processing_latency_ms", "Time to process a batch of chain creation requests in milliseconds", &["result"], exponential_bucket_interval(0.5, 8000.0), ) }); pub static QUEUE_SIZE: LazyLock<HistogramVec> = LazyLock::new(|| { register_histogram_vec( "faucet_queue_size", "Number of pending claim requests in the queue", &[], Some(vec![ 0.0, 1.0, 2.0, 5.0, 10.0, 20.0, 50.0, 100.0, 200.0, 500.0, ]), ) }); pub static QUEUE_WAIT_TIME: LazyLock<HistogramVec> = LazyLock::new(|| { register_histogram_vec( "faucet_queue_wait_time_ms", "Time a request spends in the queue before processing in milliseconds", &[], exponential_bucket_interval(0.5, 2000.0), ) }); pub static FAUCET_BALANCE: LazyLock<IntGaugeVec> = LazyLock::new(|| { register_int_gauge_vec( "faucet_balance_amount", "Current balance of the faucet chain", &[], ) }); pub static RATE_LIMIT_REJECTIONS: LazyLock<IntCounterVec> = LazyLock::new(|| { register_int_counter_vec( "faucet_rate_limit_rejections_total", "Number of requests rejected due to rate limiting", &[], ) }); pub static INSUFFICIENT_BALANCE_REJECTIONS: LazyLock<IntCounterVec> = LazyLock::new(|| { register_int_counter_vec( "faucet_insufficient_balance_rejections_total", "Number of requests rejected due to insufficient faucet balance", &[], ) }); pub static DATABASE_OPERATION_LATENCY: LazyLock<HistogramVec> = LazyLock::new(|| { register_histogram_vec( "faucet_database_operation_latency_ms", "Database operation latency in milliseconds", &["operation"], exponential_bucket_interval(0.5, 2000.0), ) }); pub static RETRYABLE_ERRORS: LazyLock<IntCounterVec> = LazyLock::new(|| { register_int_counter_vec( "faucet_retryable_errors_total", "Number of chain execution retryable errors by type", &["error_type"], ) }); } /// Returns an HTML response constructing the GraphiQL web page for the given URI. pub(crate) async fn graphiql(uri: axum::http::Uri) -> impl axum::response::IntoResponse { axum::response::Html( async_graphql::http::GraphiQLSource::build() .endpoint(uri.path()) .subscription_endpoint("/ws") .finish(), ) } #[cfg(test)] mod tests; /// The root GraphQL query type. pub struct QueryRoot<C: ClientContext> { client: ChainClient<C::Environment>, genesis_config: Arc<GenesisConfig>, faucet_storage: Arc<FaucetDatabase>, } /// The root GraphQL mutation type. pub struct MutationRoot<S> { faucet_storage: Arc<FaucetDatabase>, pending_requests: Arc<Mutex<VecDeque<PendingRequest>>>, request_notifier: Arc<Notify>, storage: S, } /// The result of a successful `claim` mutation. #[derive(SimpleObject)] pub struct ClaimOutcome { /// The ID of the new chain. pub chain_id: ChainId, /// The hash of the parent chain's certificate containing the `OpenChain` operation. pub certificate_hash: CryptoHash, } #[derive(Debug, Deserialize, SimpleObject)] pub struct Validator { pub public_key: ValidatorPublicKey, pub network_address: String, } /// A pending chain creation request. #[derive(Debug)] struct PendingRequest { owner: AccountOwner, responder: oneshot::Sender<Result<ChainDescription, Error>>, #[cfg(with_metrics)] queued_at: std::time::Instant, } /// Configuration for the batch processor. struct BatchProcessorConfig { amount: Amount, end_timestamp: Timestamp, start_timestamp: Timestamp, start_balance: Amount, max_batch_size: usize, } /// Batching coordinator for processing chain creation requests. struct BatchProcessor<C: ClientContext> { config: BatchProcessorConfig, context: Arc<Mutex<C>>, client: ChainClient<C::Environment>, faucet_storage: Arc<FaucetDatabase>, pending_requests: Arc<Mutex<VecDeque<PendingRequest>>>, request_notifier: Arc<Notify>, } #[async_graphql::Object(cache_control(no_cache))] impl<C> QueryRoot<C> where C: ClientContext + 'static, { /// Returns the version information on this faucet service. async fn version(&self) -> linera_version::VersionInfo { linera_version::VersionInfo::default() } /// Returns the genesis config. async fn genesis_config(&self) -> Result<serde_json::Value, Error> { Ok(serde_json::to_value(&*self.genesis_config)?) } /// Returns the current committee's validators. async fn current_validators(&self) -> Result<Vec<Validator>, Error> { let committee = self.client.local_committee().await?; Ok(committee .validators() .iter() .map(|(public_key, validator)| Validator { public_key: *public_key, network_address: validator.network_address.clone(), }) .collect()) } /// Returns the current committee, including weights and resource policy. async fn current_committee(&self) -> Result<Committee, Error> { Ok(self.client.local_committee().await?) } /// Find the existing a chain with the given authentication key, if any. async fn chain_id(&self, owner: AccountOwner) -> Result<ChainId, Error> { // Check if this owner already has a chain. #[cfg(with_metrics)] let db_start_time = std::time::Instant::now(); let chain_id = self .faucet_storage .get_chain_id(&owner) .await .map_err(|e| Error::new(e.to_string()))?; #[cfg(with_metrics)] metrics::DATABASE_OPERATION_LATENCY .with_label_values(&["get_chain_id"]) .observe(db_start_time.elapsed().as_secs_f64() * 1000.0); chain_id.ok_or(Error::new("This user has no chain yet")) } } #[async_graphql::Object(cache_control(no_cache))] impl<S> MutationRoot<S> where S: Storage + Send + Sync + 'static, { /// Creates a new chain with the given authentication key, and transfers tokens to it. async fn claim(&self, owner: AccountOwner) -> Result<ChainDescription, Error> { #[cfg(with_metrics)] let start_time = std::time::Instant::now(); let result = self.do_claim(owner).await; #[cfg(with_metrics)] { let label = if result.is_ok() { "success" } else { "error" }; metrics::CLAIM_LATENCY .with_label_values(&[label]) .observe(start_time.elapsed().as_secs_f64() * 1000.0); } result } } impl<S> MutationRoot<S> where S: Storage + Send + Sync + 'static, { async fn do_claim(&self, owner: AccountOwner) -> Result<ChainDescription, Error> { // Check if this owner already has a chain. #[cfg(with_metrics)] let db_start_time = std::time::Instant::now(); let existing_chain_id = self .faucet_storage .get_chain_id(&owner) .await .map_err(|e| Error::new(e.to_string()))?; #[cfg(with_metrics)] metrics::DATABASE_OPERATION_LATENCY .with_label_values(&["get_chain_id"]) .observe(db_start_time.elapsed().as_secs_f64() * 1000.0); if let Some(existing_chain_id) = existing_chain_id { #[cfg(with_metrics)] metrics::CLAIM_REQUESTS_TOTAL .with_label_values(&["duplicate"]) .inc(); // Retrieve the chain description from local storage return get_chain_description_from_storage(&self.storage, existing_chain_id).await; } // Create a oneshot channel to receive the result. let (tx, rx) = oneshot::channel(); // Add request to the queue. { let mut requests = self.pending_requests.lock().await; requests.push_back(PendingRequest { owner, responder: tx, #[cfg(with_metrics)] queued_at: std::time::Instant::now(), }); #[cfg(with_metrics)] metrics::QUEUE_SIZE .with_label_values(&[]) .observe(requests.len() as f64); } // Notify the batch processor that there's a new request. self.request_notifier.notify_one(); // Wait for the result let result = rx .await .map_err(|_| Error::new("Request processing was cancelled"))?; #[cfg(with_metrics)] { let label = if result.is_ok() { "success" } else { "error" }; metrics::CLAIM_REQUESTS_TOTAL .with_label_values(&[label]) .inc(); } result } } /// Multiplies a `u128` with a `u64` and returns the result as a 192-bit number. fn multiply(a: u128, b: u64) -> [u64; 3] { let lower = u128::from(u64::MAX); let b = u128::from(b); let mut a1 = (a >> 64) * b; let a0 = (a & lower) * b; a1 += a0 >> 64; [(a1 >> 64) as u64, (a1 & lower) as u64, (a0 & lower) as u64] } /// Retrieves a chain description from storage by reading the blob directly. /// /// This function handles errors appropriately and returns a GraphQL-compatible result. async fn get_chain_description_from_storage<S>( storage: &S, chain_id: ChainId, ) -> Result<ChainDescription, Error> where S: Storage, { // Create blob ID from chain ID - the chain ID is the hash of the chain description blob let blob_id = BlobId::new(chain_id.0, BlobType::ChainDescription); // Read the blob directly from storage let blob = storage .read_blob(blob_id) .await .map_err(|e| { tracing::error!( "Failed to read chain description blob for {}: {}", chain_id, e ); Error::new(format!( "Storage error while reading chain description: {e}" )) })? .ok_or_else(|| { tracing::error!("Chain description blob not found for chain {}", chain_id); Error::new(format!( "Chain description not found for chain {}", chain_id )) })?; // Deserialize the chain description from the blob bytes let description = bcs::from_bytes::<ChainDescription>(blob.bytes()).map_err(|e| { tracing::error!( "Failed to deserialize chain description for {}: {}", chain_id, e ); Error::new(format!( "Invalid chain description data for chain {}", chain_id )) })?; Ok(description) } impl<C> BatchProcessor<C> where C: ClientContext + 'static, { /// Creates a new batch processor. fn new( config: BatchProcessorConfig, context: Arc<Mutex<C>>, client: ChainClient<C::Environment>, faucet_storage: Arc<FaucetDatabase>, pending_requests: Arc<Mutex<VecDeque<PendingRequest>>>, request_notifier: Arc<Notify>, ) -> Self { Self { config, context, client, faucet_storage, pending_requests, request_notifier, } } /// Runs the batch processor loop. async fn run(&mut self, cancellation_token: CancellationToken) { loop { tokio::select! { _ = self.request_notifier.notified() => { if let Err(e) = self.process_batch().await { tracing::error!("Batch processing error: {}", e); } } _ = cancellation_token.cancelled() => { // Process any remaining requests before shutting down if let Err(e) = self.process_batch().await { tracing::error!("Final batch processing error: {}", e); } break; } } } } /// Processes batches until there are no more pending requests in the queue. async fn process_batch(&mut self) -> anyhow::Result<()> { loop { let batch_requests = self.get_request_batch().await; if batch_requests.is_empty() { return Ok(()); } let batch_size = batch_requests.len(); tracing::info!("Processing batch of {} requests", batch_size); #[cfg(with_metrics)] { metrics::BATCH_SIZE .with_label_values(&[]) .observe(batch_size as f64); metrics::QUEUE_SIZE.with_label_values(&[]).observe(0.0); } #[cfg(with_metrics)] let batch_start_time = std::time::Instant::now(); let batch_result = self.execute_batch(batch_requests).await; #[cfg(with_metrics)] { let elapsed_ms = batch_start_time.elapsed().as_secs_f64() * 1000.0; let label = if batch_result.is_ok() { "success" } else { "error" }; metrics::BATCH_PROCESSING_LATENCY .with_label_values(&[label]) .observe(elapsed_ms); } if let Err(err) = batch_result { tracing::error!("Failed to execute batch: {}", err); return Err(err); } } } // Collects requests for new accounts from the queue; answers the ones for existing // accounts immediately. async fn get_request_batch(&mut self) -> Vec<PendingRequest> { let mut batch_requests = Vec::new(); let mut requests = self.pending_requests.lock().await; while batch_requests.len() < self.config.max_batch_size { let Some(request) = requests.pop_front() else { break; }; // Check if this owner already has a chain. Otherwise send response immediately. let response = match self.faucet_storage.get_chain_id(&request.owner).await { Ok(None) => { batch_requests.push(request); continue; } Ok(Some(existing_chain_id)) => { // Retrieve the chain description from local storage. get_chain_description_from_storage( self.client.storage_client(), existing_chain_id, ) .await } Err(err) => { tracing::error!("Database error: {err}"); Err(Error::new(err.to_string())) } }; if let Err(response) = request.responder.send(response) { tracing::error!( "Receiver dropped while sending response {response:?} for request from {}", request.owner ); } } batch_requests } /// Checks if the given number of requests can currently be fulfilled, based on the balance /// and rate limiting settings. Returns an error if not. async fn check_rate_limiting(&self, request_count: usize) -> async_graphql::Result<()> { let end_timestamp = self.config.end_timestamp; let start_timestamp = self.config.start_timestamp; let local_time = self.client.storage_client().clock().current_time(); let full_duration = end_timestamp.delta_since(start_timestamp).as_micros(); let remaining_duration = end_timestamp.delta_since(local_time).as_micros(); let balance = self.client.local_balance().await?; #[cfg(with_metrics)] metrics::FAUCET_BALANCE .with_label_values(&[]) .set(u128::from(balance) as i64); let total_amount = self.config.amount.saturating_mul(request_count as u128); let Ok(remaining_balance) = balance.try_sub(total_amount) else { // Not enough balance - reject all requests #[cfg(with_metrics)] metrics::INSUFFICIENT_BALANCE_REJECTIONS .with_label_values(&[]) .inc(); return Err(Error::new("The faucet is empty.")); }; // Rate limit: Locked token balance decreases lineraly with time, i.e.: // remaining_balance / remaining_duration >= start_balance / full_duration if multiply(u128::from(self.config.start_balance), remaining_duration) > multiply(u128::from(remaining_balance), full_duration) { #[cfg(with_metrics)] metrics::RATE_LIMIT_REJECTIONS.with_label_values(&[]).inc(); return Err(Error::new("Not enough unlocked balance; try again later.")); } Ok(()) } /// Sends an error response to all requestors. fn send_err(requests: Vec<PendingRequest>, err: impl Into<async_graphql::Error>) { let err = err.into(); for request in requests { if request.responder.send(Err(err.clone())).is_err() { tracing::warn!("Receiver dropped while sending error to {}.", request.owner); } } } /// Executes a batch of chain creation requests. async fn execute_batch(&mut self, requests: Vec<PendingRequest>) -> anyhow::Result<()> { if let Err(err) = self.check_rate_limiting(requests.len()).await { tracing::debug!("Rejecting requests due to rate limiting: {err:?}"); Self::send_err(requests, err); return Ok(()); } // Create OpenChain operations for all valid requests let mut operations = Vec::new(); for request in &requests { let config = OpenChainConfig { ownership: ChainOwnership::single(request.owner), balance: self.config.amount, application_permissions: ApplicationPermissions::default(), }; operations.push(Operation::system(SystemOperation::OpenChain(config))); } // Execute all operations in a single block let result = self.client.execute_operations(operations, vec![]).await; self.context .lock() .await .update_wallet(&self.client) .await?; let certificate = match result { Err(chain_client::Error::LocalNodeError(LocalNodeError::WorkerError( WorkerError::ChainError(chain_err), ))) => { tracing::debug!("Local worker error executing operations: {chain_err}"); match *chain_err { ChainError::ExecutionError(exec_err, ChainExecutionContext::Operation(i)) if i > 0 && matches!( *exec_err, ExecutionError::BlockTooLarge | ExecutionError::FeesExceedFunding { .. } | ExecutionError::InsufficientBalance { .. } | ExecutionError::MaximumFuelExceeded(_) ) => { tracing::error!(%exec_err, "Execution of operation {i} failed; reducing batch size"); #[cfg(with_metrics)] { let error_type = match *exec_err { ExecutionError::BlockTooLarge => "block_too_large", ExecutionError::FeesExceedFunding { .. } => "fees_exceed_funding", ExecutionError::InsufficientBalance { .. } => { "insufficient_balance" } ExecutionError::MaximumFuelExceeded(_) => "fuel_exceeded", _ => "other", }; metrics::RETRYABLE_ERRORS .with_label_values(&[error_type]) .inc(); } self.config.max_batch_size = i as usize; // Put the valid requests back into the queue. let mut pending_requests = self.pending_requests.lock().await; for request in requests.into_iter().rev() { pending_requests.push_front(request); } return Ok(()); // Don't return an error, so we retry. } chain_err => { Self::send_err(requests, chain_err.to_string()); return Err(chain_client::Error::LocalNodeError( LocalNodeError::WorkerError(WorkerError::ChainError(chain_err.into())), ) .into()); } } } Err(err) => { tracing::debug!("Error executing operations: {err}"); Self::send_err(requests, err.to_string()); return Err(err.into()); } Ok(ClientOutcome::Committed(certificate)) => certificate, Ok(ClientOutcome::WaitForTimeout(timeout)) => { let error_msg = format!( "This faucet is using a multi-owner chain and is not the leader right now. \ Try again at {}", timeout.timestamp, ); Self::send_err(requests, error_msg.clone()); return Ok(()); } }; // Parse chain descriptions from the block's blobs let chain_descriptions = extract_opened_single_owner_chains(&certificate)?; if chain_descriptions.len() != requests.len() { let error_msg = format!( "Mismatch between operations ({}) and results ({})", requests.len(), chain_descriptions.len() ); Self::send_err(requests, error_msg.clone()); anyhow::bail!(error_msg); } // Store results. let chains_to_store = chain_descriptions .iter() .map(|(owner, description)| (*owner, description.id())) .collect(); if let Err(e) = self .faucet_storage .store_chains_batch(chains_to_store) .await { let error_msg = format!("Failed to save chains to database: {}", e); Self::send_err(requests, error_msg.clone()); anyhow::bail!(error_msg); } // Respond to requests. #[cfg(with_metrics)] let chains_created = chain_descriptions.len(); for (request, (owner, description)) in requests.into_iter().zip(chain_descriptions) { #[cfg(with_metrics)] { let wait_time = request.queued_at.elapsed().as_secs_f64() * 1000.0; metrics::QUEUE_WAIT_TIME .with_label_values(&[]) .observe(wait_time); } let response = if request.owner == owner { Ok(description) } else { let error_msg = format!( "Owner mismatch: description for {owner}, but requested by {}", request.owner ); tracing::error!("{}", error_msg); Err(Error::new(error_msg)) }; if request.responder.send(response).is_err() { tracing::warn!("Receiver dropped while sending response to {owner}."); } } #[cfg(with_metrics)] metrics::CHAINS_CREATED_TOTAL .with_label_values(&[]) .inc_by(chains_created as u64); Ok(()) } } /// A GraphQL interface to request a new chain with tokens. pub struct FaucetService<C> where C: ClientContext, { chain_id: ChainId, context: Arc<Mutex<C>>, client: ChainClient<C::Environment>, genesis_config: Arc<GenesisConfig>, config: ChainListenerConfig, storage: <C::Environment as linera_core::Environment>::Storage, port: u16, #[cfg(feature = "metrics")] metrics_port: u16, amount: Amount, end_timestamp: Timestamp, start_timestamp: Timestamp, start_balance: Amount, faucet_storage: Arc<FaucetDatabase>, storage_path: PathBuf, /// Batching components pending_requests: Arc<Mutex<VecDeque<PendingRequest>>>, request_notifier: Arc<Notify>, max_batch_size: usize, } impl<C> Clone for FaucetService<C> where C: ClientContext + 'static, { fn clone(&self) -> Self { Self { chain_id: self.chain_id, context: Arc::clone(&self.context), client: self.client.clone(), genesis_config: Arc::clone(&self.genesis_config), config: self.config.clone(), storage: self.storage.clone(), port: self.port, #[cfg(feature = "metrics")] metrics_port: self.metrics_port, amount: self.amount, end_timestamp: self.end_timestamp, start_timestamp: self.start_timestamp, start_balance: self.start_balance, faucet_storage: Arc::clone(&self.faucet_storage), storage_path: self.storage_path.clone(), pending_requests: Arc::clone(&self.pending_requests), request_notifier: Arc::clone(&self.request_notifier), max_batch_size: self.max_batch_size, } } } pub struct FaucetConfig { pub port: u16, #[cfg(feature = "metrics")] pub metrics_port: u16, pub chain_id: ChainId, pub amount: Amount, pub end_timestamp: Timestamp, pub genesis_config: std::sync::Arc<GenesisConfig>, pub chain_listener_config: ChainListenerConfig, pub storage_path: PathBuf, pub max_batch_size: usize, } impl<C> FaucetService<C> where C: ClientContext + 'static, { /// Creates a new instance of the faucet service. pub async fn new(config: FaucetConfig, context: C) -> anyhow::Result<Self> { let storage = context.storage().clone(); let client = context.make_chain_client(config.chain_id).await?; let context = Arc::new(Mutex::new(context)); let start_timestamp = client.storage_client().clock().current_time(); client.process_inbox().await?; let start_balance = client.local_balance().await?; // Use provided storage path let storage_path = config.storage_path.clone(); // Initialize database. let faucet_storage = FaucetDatabase::new(&storage_path) .await .context("Failed to initialize faucet database")?; // Synchronize database with blockchain history. if let Err(e) = faucet_storage.sync_with_blockchain(&client).await { tracing::warn!("Failed to synchronize database with blockchain: {}", e); } let faucet_storage = Arc::new(faucet_storage); // Initialize batching components let pending_requests = Arc::new(Mutex::new(VecDeque::new())); let request_notifier = Arc::new(Notify::new()); Ok(Self { chain_id: config.chain_id, storage, context, client, genesis_config: config.genesis_config, config: config.chain_listener_config, port: config.port, #[cfg(feature = "metrics")] metrics_port: config.metrics_port, amount: config.amount, end_timestamp: config.end_timestamp, start_timestamp, start_balance, faucet_storage, storage_path, pending_requests, request_notifier, max_batch_size: config.max_batch_size, }) } fn schema( &self, ) -> Schema< QueryRoot<C>, MutationRoot<<C::Environment as linera_core::Environment>::Storage>, EmptySubscription, > { let mutation_root = MutationRoot { faucet_storage: Arc::clone(&self.faucet_storage), pending_requests: Arc::clone(&self.pending_requests), request_notifier: Arc::clone(&self.request_notifier), storage: self.storage.clone(), }; let query_root = QueryRoot { genesis_config: Arc::clone(&self.genesis_config), client: self.client.clone(), faucet_storage: Arc::clone(&self.faucet_storage), }; Schema::build(query_root, mutation_root, EmptySubscription).finish() } #[cfg(feature = "metrics")] fn metrics_address(&self) -> SocketAddr { SocketAddr::from(([0, 0, 0, 0], self.metrics_port)) } /// Runs the faucet. #[tracing::instrument(name = "FaucetService::run", skip_all, fields(port = self.port, chain_id = ?self.chain_id))] pub async fn run(self, cancellation_token: CancellationToken) -> anyhow::Result<()> { let port = self.port;
rust
Apache-2.0
69f159d2106f7fc70870ce70074c55850bf1303b
2026-01-04T15:33:08.660695Z
true
linera-io/linera-protocol
https://github.com/linera-io/linera-protocol/blob/69f159d2106f7fc70870ce70074c55850bf1303b/linera-faucet/server/src/tests.rs
linera-faucet/server/src/tests.rs
// Copyright (c) Zefchain Labs, Inc. // SPDX-License-Identifier: Apache-2.0 #![allow(clippy::large_futures)] use std::{collections::VecDeque, sync::Arc}; use futures::lock::Mutex; use linera_base::{ crypto::{AccountPublicKey, CryptoHash, InMemorySigner, TestString}, data_types::{Amount, Epoch, Timestamp}, identifiers::{AccountOwner, ChainId}, }; use linera_client::chain_listener; use linera_core::{ client::ChainClient, environment, test_utils::{MemoryStorageBuilder, StorageBuilder, TestBuilder}, }; use linera_execution::ResourceControlPolicy; use tempfile::tempdir; use tokio::sync::{oneshot, Notify}; use tokio_util::sync::CancellationToken; use crate::database::FaucetDatabase; struct ClientContext { client: ChainClient<environment::Test>, update_calls: usize, } impl chain_listener::ClientContext for ClientContext { type Environment = environment::Test; fn wallet(&self) -> &environment::TestWallet { unimplemented!() } fn storage(&self) -> &environment::TestStorage { self.client.storage_client() } fn client(&self) -> &Arc<linera_core::client::Client<environment::Test>> { unimplemented!() } fn timing_sender( &self, ) -> Option<tokio::sync::mpsc::UnboundedSender<(u64, linera_core::client::TimingType)>> { None } async fn make_chain_client( &self, chain_id: ChainId, ) -> Result<ChainClient<environment::Test>, linera_client::Error> { assert_eq!(chain_id, self.client.chain_id()); Ok(self.client.clone()) } async fn update_wallet_for_new_chain( &mut self, _: ChainId, _: Option<AccountOwner>, _: Timestamp, _: Epoch, ) -> Result<(), linera_client::Error> { self.update_calls += 1; Ok(()) } async fn update_wallet( &mut self, _: &ChainClient<environment::Test>, ) -> Result<(), linera_client::Error> { self.update_calls += 1; Ok(()) } } #[tokio::test] async fn test_faucet_rate_limiting() { let storage_builder = MemoryStorageBuilder::default(); let keys = InMemorySigner::new(None); let clock = storage_builder.clock().clone(); clock.set(Timestamp::from(0)); let mut builder = TestBuilder::new(storage_builder, 4, 1, keys).await.unwrap(); let client = builder .add_root_chain(1, Amount::from_tokens(6)) .await .unwrap(); let context = ClientContext { client: client.clone(), update_calls: 0, }; let context = Arc::new(Mutex::new(context)); let temp_dir = tempdir().unwrap(); let faucet_storage = Arc::new( FaucetDatabase::new(&temp_dir.path().join("test_faucet_rate_limiting.sqlite")) .await .unwrap(), ); // Set up the batching components let pending_requests = Arc::new(Mutex::new(VecDeque::new())); let request_notifier = Arc::new(Notify::new()); // Create the MutationRoot with the current structure let root = super::MutationRoot { faucet_storage: Arc::clone(&faucet_storage), pending_requests: Arc::clone(&pending_requests), request_notifier: Arc::clone(&request_notifier), storage: client.storage_client().clone(), }; // Create the BatchProcessor configuration and instance let batch_config = super::BatchProcessorConfig { amount: Amount::from_tokens(1), end_timestamp: Timestamp::from(6000), start_timestamp: Timestamp::from(0), start_balance: Amount::from_tokens(6), max_batch_size: 1, }; let batch_processor = super::BatchProcessor::new( batch_config, Arc::clone(&context), client, Arc::clone(&faucet_storage), Arc::clone(&pending_requests), Arc::clone(&request_notifier), ); // Start the batch processor in the background let cancellation_token = CancellationToken::new(); let processor_task = { let mut batch_processor = batch_processor; let token = cancellation_token.clone(); tokio::spawn(async move { batch_processor.run(token).await }) }; // The faucet is releasing one token every 1000 microseconds. So at 1000 one claim should // succeed. At 3000, two more should have been unlocked. // Test: at time 999, no claims should succeed due to rate limiting clock.set(Timestamp::from(999)); let result1 = root.do_claim(AccountPublicKey::test_key(0).into()).await; assert!( result1.is_err(), "Claim should fail before rate limit allows" ); // Test: at time 1000, first claim should succeed clock.set(Timestamp::from(1000)); let result2 = root.do_claim(AccountPublicKey::test_key(1).into()).await; assert!(result2.is_ok(), "First claim should succeed at time 1000"); // Test: immediate second claim should fail (rate limit) let result3 = root.do_claim(AccountPublicKey::test_key(2).into()).await; assert!( result3.is_err(), "Second immediate claim should fail due to rate limit" ); // Test: at time 3000, more tokens should be available clock.set(Timestamp::from(3000)); let result4 = root.do_claim(AccountPublicKey::test_key(3).into()).await; assert!(result4.is_ok(), "Third claim should succeed at time 3000"); let result5 = root.do_claim(AccountPublicKey::test_key(4).into()).await; assert!(result5.is_ok(), "Fourth claim should succeed at time 3000"); // Test: too many claims should eventually fail let result6 = root.do_claim(AccountPublicKey::test_key(5).into()).await; assert!( result6.is_err(), "Fifth claim should fail due to rate limit" ); // Verify update_wallet calls (includes successful operations and final error case) let update_calls = context.lock().await.update_calls; assert_eq!(update_calls, 3); // Clean up cancellation_token.cancel(); let _ = processor_task.await; } #[test] fn test_multiply() { use super::multiply; assert_eq!( multiply((1 << 127) + (1 << 63), 1 << 63), [1 << 62, 1 << 62, 0] ); assert_eq!(multiply(u128::MAX, u64::MAX), [u64::MAX - 1, u64::MAX, 1]); } #[test_log::test(tokio::test)] async fn test_batch_size_reduction_on_limit_errors() { // Test that the batch processor reduces batch size when hitting BlockTooLarge limit // Set up test environment let temp_dir = tempdir().unwrap(); let storage_path = temp_dir.path().join("test_batch_reduction.sqlite"); let storage_builder = MemoryStorageBuilder::default(); let keys = InMemorySigner::new(None); // Create a restrictive policy that limits block size to trigger BlockTooLarge let restrictive_policy = ResourceControlPolicy { maximum_block_size: 800, ..ResourceControlPolicy::default() }; let mut builder = TestBuilder::new(storage_builder, 4, 1, keys) .await .unwrap() .with_policy(restrictive_policy); let client = builder .add_root_chain(1, Amount::from_tokens(100)) .await .unwrap(); let context = Arc::new(Mutex::new(ClientContext { client: client.clone(), update_calls: 0, })); let faucet_storage = Arc::new(FaucetDatabase::new(&storage_path).await.unwrap()); let pending_requests = Arc::new(Mutex::new(VecDeque::new())); let request_notifier = Arc::new(Notify::new()); // Create batch processor with initial batch size of 3 and disabled rate limiting let initial_batch_size = 3; let config = super::BatchProcessorConfig { amount: Amount::from_tokens(1), start_balance: Amount::from_tokens(100), start_timestamp: Timestamp::from(0), end_timestamp: Timestamp::from(0), // All tokens are unlocked: no rate limiting. max_batch_size: initial_batch_size, }; let mut batch_processor = super::BatchProcessor::new( config, Arc::clone(&context), client, Arc::clone(&faucet_storage), Arc::clone(&pending_requests), Arc::clone(&request_notifier), ); // Create 3 different owners for batch processing let owners = [ CryptoHash::new(&TestString("owner1".into())).into(), CryptoHash::new(&TestString("owner2".into())).into(), CryptoHash::new(&TestString("owner3".into())).into(), ]; // Create and queue 3 pending requests { let mut pending_requests_guard = pending_requests.lock().await; for owner in owners { let (tx, _rx) = oneshot::channel(); pending_requests_guard.push_back(super::PendingRequest { owner, responder: tx, #[cfg(with_metrics)] queued_at: std::time::Instant::now(), }); } } // Execute the batch - this triggers BlockTooLarge error batch_processor .process_batch() .await .expect("Batch processing should succeed"); // Now the batch size should be reduced. assert!(batch_processor.config.max_batch_size < initial_batch_size); } #[test_log::test(tokio::test)] async fn test_faucet_persistence() { // Test that the faucet correctly persists chain IDs and retrieves them after restart. // This ensures the database is working correctly across sessions. let storage_builder = MemoryStorageBuilder::default(); let keys = InMemorySigner::new(None); let clock = storage_builder.clock().clone(); clock.set(Timestamp::from(0)); let mut builder = TestBuilder::new(storage_builder, 4, 1, keys).await.unwrap(); let client = builder .add_root_chain(1, Amount::from_tokens(6)) .await .unwrap(); let temp_dir = tempdir().unwrap(); let storage_path = temp_dir.path().join("test_faucet_persistence.sqlite"); // Create first faucet instance let faucet_storage = Arc::new(FaucetDatabase::new(&storage_path).await.unwrap()); let context = ClientContext { client: client.clone(), update_calls: 0, }; let context = Arc::new(Mutex::new(context)); // Set up the first MutationRoot instance let pending_requests = Arc::new(Mutex::new(VecDeque::new())); let request_notifier = Arc::new(Notify::new()); let root = super::MutationRoot { faucet_storage: Arc::clone(&faucet_storage), pending_requests: Arc::clone(&pending_requests), request_notifier: Arc::clone(&request_notifier), storage: client.storage_client().clone(), }; // Create the BatchProcessor configuration let batch_config = super::BatchProcessorConfig { amount: Amount::from_tokens(1), end_timestamp: Timestamp::from(6000), start_timestamp: Timestamp::from(0), start_balance: Amount::from_tokens(6), max_batch_size: 1, }; let batch_processor = super::BatchProcessor::new( batch_config, Arc::clone(&context), client.clone(), Arc::clone(&faucet_storage), Arc::clone(&pending_requests), Arc::clone(&request_notifier), ); // Start the batch processor let cancellation_token = CancellationToken::new(); let processor_task = { let mut batch_processor = batch_processor; let token = cancellation_token.clone(); tokio::spawn(async move { batch_processor.run(token).await }) }; // Set time to allow claims clock.set(Timestamp::from(1000)); // Make first claim with a specific owner let test_owner_1 = AccountPublicKey::test_key(42).into(); let test_owner_2 = AccountPublicKey::test_key(43).into(); // Claim chains for two different owners let chain_1 = root .do_claim(test_owner_1) .await .expect("First claim should succeed"); clock.set(Timestamp::from(2000)); let chain_2 = root .do_claim(test_owner_2) .await .expect("Second claim should succeed"); // Verify that immediate re-claims return the same chains let chain_1_again = root .do_claim(test_owner_1) .await .expect("Re-claim should return existing chain"); assert_eq!( chain_1.id(), chain_1_again.id(), "Should return same chain for same owner" ); let chain_2_again = root .do_claim(test_owner_2) .await .expect("Re-claim should return existing chain"); assert_eq!( chain_2.id(), chain_2_again.id(), "Should return same chain for same owner" ); // Store the chain IDs for later comparison let chain_1_id = chain_1.id(); let chain_2_id = chain_2.id(); // Stop the batch processor cancellation_token.cancel(); let _ = processor_task.await; // Drop the first faucet instance to simulate shutdown drop(root); drop(faucet_storage); // Create a new faucet instance with the same database path (simulating restart) let faucet_storage_2 = Arc::new(FaucetDatabase::new(&storage_path).await.unwrap()); // Test the chain_id query API through the database for owners that have claimed chains let queried_chain_1 = faucet_storage_2 .get_chain_id(&test_owner_1) .await .expect("Query should succeed for owner 1") .expect("Owner 1 should have a chain ID"); assert_eq!( chain_1_id, queried_chain_1, "Query should return correct chain ID for owner 1" ); let queried_chain_2 = faucet_storage_2 .get_chain_id(&test_owner_2) .await .expect("Query should succeed for owner 2") .expect("Owner 2 should have a chain ID"); assert_eq!( chain_2_id, queried_chain_2, "Query should return correct chain ID for owner 2" ); // Test the chain_id query for an owner that hasn't claimed a chain yet let test_owner_new = AccountPublicKey::test_key(99).into(); let result_new = faucet_storage_2 .get_chain_id(&test_owner_new) .await .expect("Query should succeed even for non-existent owner"); assert!( result_new.is_none(), "Query should return None for owner that hasn't claimed a chain" ); // Set up the new MutationRoot instance let pending_requests_2 = Arc::new(Mutex::new(VecDeque::new())); let request_notifier_2 = Arc::new(Notify::new()); let root_2 = super::MutationRoot { faucet_storage: Arc::clone(&faucet_storage_2), pending_requests: Arc::clone(&pending_requests_2), request_notifier: Arc::clone(&request_notifier_2), storage: client.storage_client().clone(), }; // Create new batch processor for the second instance let batch_config_2 = super::BatchProcessorConfig { amount: Amount::from_tokens(1), end_timestamp: Timestamp::from(6000), start_timestamp: Timestamp::from(0), start_balance: Amount::from_tokens(6), max_batch_size: 1, }; let batch_processor_2 = super::BatchProcessor::new( batch_config_2, Arc::clone(&context), client.clone(), Arc::clone(&faucet_storage_2), Arc::clone(&pending_requests_2), Arc::clone(&request_notifier_2), ); // Start the new batch processor let cancellation_token_2 = CancellationToken::new(); let processor_task_2 = { let mut batch_processor = batch_processor_2; let token = cancellation_token_2.clone(); tokio::spawn(async move { batch_processor.run(token).await }) }; // Verify that the new instance returns the same chain IDs for the same owners let chain_1_after_restart = root_2 .do_claim(test_owner_1) .await .expect("Should return existing chain after restart"); assert_eq!( chain_1_id, chain_1_after_restart.id(), "Chain ID should be preserved after restart for owner 1" ); let chain_2_after_restart = root_2 .do_claim(test_owner_2) .await .expect("Should return existing chain after restart"); assert_eq!( chain_2_id, chain_2_after_restart.id(), "Chain ID should be preserved after restart for owner 2" ); // Verify that a new owner can still claim a new chain after restart clock.set(Timestamp::from(3000)); let test_owner_3 = AccountPublicKey::test_key(44).into(); let chain_3 = root_2 .do_claim(test_owner_3) .await .expect("New owner should be able to claim after restart"); // Verify the new chain is different from the existing ones assert_ne!( chain_3.id(), chain_1_id, "New chain should have different ID" ); assert_ne!( chain_3.id(), chain_2_id, "New chain should have different ID" ); // Clean up cancellation_token_2.cancel(); let _ = processor_task_2.await; } #[test_log::test(tokio::test)] async fn test_blockchain_sync_after_database_deletion() { // Test that the faucet correctly syncs with blockchain after database deletion. // This verifies that the blockchain synchronization can restore chain mappings from // the blockchain history when the database is lost or corrupted. let storage_builder = MemoryStorageBuilder::default(); let keys = InMemorySigner::new(None); let clock = storage_builder.clock().clone(); clock.set(Timestamp::from(0)); let mut builder = TestBuilder::new(storage_builder, 4, 1, keys).await.unwrap(); let client = builder .add_root_chain(1, Amount::from_tokens(6)) .await .unwrap(); let temp_dir = tempdir().unwrap(); let storage_path = temp_dir.path().join("test_blockchain_sync.sqlite"); // === PHASE 1: Create chains with first faucet instance === let faucet_storage = Arc::new(FaucetDatabase::new(&storage_path).await.unwrap()); let context = ClientContext { client: client.clone(), update_calls: 0, }; let context = Arc::new(Mutex::new(context)); // Set up the first MutationRoot instance let pending_requests = Arc::new(Mutex::new(VecDeque::new())); let request_notifier = Arc::new(Notify::new()); let root = super::MutationRoot { faucet_storage: Arc::clone(&faucet_storage), pending_requests: Arc::clone(&pending_requests), request_notifier: Arc::clone(&request_notifier), storage: client.storage_client().clone(), }; // Create the BatchProcessor configuration let batch_config = super::BatchProcessorConfig { amount: Amount::from_tokens(1), end_timestamp: Timestamp::from(6000), start_timestamp: Timestamp::from(0), start_balance: Amount::from_tokens(6), max_batch_size: 1, }; let batch_processor = super::BatchProcessor::new( batch_config, Arc::clone(&context), client.clone(), Arc::clone(&faucet_storage), Arc::clone(&pending_requests), Arc::clone(&request_notifier), ); // Start the batch processor let cancellation_token = CancellationToken::new(); let processor_task = { let mut batch_processor = batch_processor; let token = cancellation_token.clone(); tokio::spawn(async move { batch_processor.run(token).await }) }; // Set time to allow claims clock.set(Timestamp::from(1000)); // Make claims with specific owners to create chain mappings let test_owner_1 = AccountPublicKey::test_key(100).into(); let test_owner_2 = AccountPublicKey::test_key(101).into(); // Claim chains for two different owners let chain_1 = root .do_claim(test_owner_1) .await .expect("First claim should succeed"); clock.set(Timestamp::from(2000)); let chain_2 = root .do_claim(test_owner_2) .await .expect("Second claim should succeed"); // Store the chain IDs for later comparison let chain_1_id = chain_1.id(); let chain_2_id = chain_2.id(); // Verify initial state works correctly let chain_1_again = root .do_claim(test_owner_1) .await .expect("Re-claim should return existing chain"); assert_eq!( chain_1_id, chain_1_again.id(), "Should return same chain for same owner initially" ); // Stop the batch processor and clean up first instance cancellation_token.cancel(); let _ = processor_task.await; drop(root); drop(faucet_storage); // === PHASE 2: Delete the database file (simulate data loss) === std::fs::remove_file(&storage_path).expect("Should be able to delete database file"); // === PHASE 3: Create new faucet instance (should sync from blockchain) === let faucet_storage_2 = Arc::new(FaucetDatabase::new(&storage_path).await.unwrap()); // CRITICAL: Trigger blockchain sync before using the faucet faucet_storage_2 .sync_with_blockchain(&client) .await .expect("Blockchain sync should succeed"); // Set up the new MutationRoot instance let pending_requests_2 = Arc::new(Mutex::new(VecDeque::new())); let request_notifier_2 = Arc::new(Notify::new()); let root_2 = super::MutationRoot { faucet_storage: Arc::clone(&faucet_storage_2), pending_requests: Arc::clone(&pending_requests_2), request_notifier: Arc::clone(&request_notifier_2), storage: client.storage_client().clone(), }; // Create new batch processor for the second instance let batch_config_2 = super::BatchProcessorConfig { amount: Amount::from_tokens(1), end_timestamp: Timestamp::from(6000), start_timestamp: Timestamp::from(0), start_balance: Amount::from_tokens(6), max_batch_size: 1, }; let batch_processor_2 = super::BatchProcessor::new( batch_config_2, Arc::clone(&context), client.clone(), Arc::clone(&faucet_storage_2), Arc::clone(&pending_requests_2), Arc::clone(&request_notifier_2), ); // Start the new batch processor let cancellation_token_2 = CancellationToken::new(); let processor_task_2 = { let mut batch_processor = batch_processor_2; let token = cancellation_token_2.clone(); tokio::spawn(async move { batch_processor.run(token).await }) }; // === PHASE 4: Verify blockchain sync restored the correct mappings === // Test that the blockchain sync correctly restored the chain mappings let chain_1_after_sync = root_2 .do_claim(test_owner_1) .await .expect("Should return existing chain after blockchain sync"); assert_eq!( chain_1_id, chain_1_after_sync.id(), "Chain ID should be correctly restored from blockchain for owner 1" ); let chain_2_after_sync = root_2 .do_claim(test_owner_2) .await .expect("Should return existing chain after blockchain sync"); assert_eq!( chain_2_id, chain_2_after_sync.id(), "Chain ID should be correctly restored from blockchain for owner 2" ); // === PHASE 5: Verify new claims still work correctly === // Verify that a completely new owner can still claim a new chain clock.set(Timestamp::from(3000)); let test_owner_3 = AccountPublicKey::test_key(102).into(); let chain_3 = root_2 .do_claim(test_owner_3) .await .expect("New owner should be able to claim after sync"); // Verify the new chain is different from the existing ones assert_ne!( chain_3.id(), chain_1_id, "New chain should have different ID from synced chains" ); assert_ne!( chain_3.id(), chain_2_id, "New chain should have different ID from synced chains" ); // Verify that the new chain mapping is also persisted let chain_3_again = root_2 .do_claim(test_owner_3) .await .expect("Re-claim should return the new chain"); assert_eq!( chain_3.id(), chain_3_again.id(), "New chain should be persistent after sync" ); // Clean up cancellation_token_2.cancel(); let _ = processor_task_2.await; }
rust
Apache-2.0
69f159d2106f7fc70870ce70074c55850bf1303b
2026-01-04T15:33:08.660695Z
false
linera-io/linera-protocol
https://github.com/linera-io/linera-protocol/blob/69f159d2106f7fc70870ce70074c55850bf1303b/linera-faucet/server/src/database.rs
linera-faucet/server/src/database.rs
// Copyright (c) Zefchain Labs, Inc. // SPDX-License-Identifier: Apache-2.0 //! SQLite database module for storing chain assignments. use std::{collections::BTreeMap, path::PathBuf}; use anyhow::Context as _; use linera_base::{ crypto::CryptoHash, data_types::BlockHeight, identifiers::{AccountOwner, ChainId}, }; use linera_core::client::ChainClient; use linera_storage::Storage; use sqlx::{ sqlite::{SqliteConnectOptions, SqlitePool, SqlitePoolOptions}, Row, }; use tracing::info; /// SQLite database for persistent storage of chain assignments. pub struct FaucetDatabase { pool: SqlitePool, } /// Schema for creating the chains table. const CREATE_CHAINS_TABLE: &str = r#" CREATE TABLE IF NOT EXISTS chains ( owner TEXT PRIMARY KEY NOT NULL, chain_id TEXT NOT NULL, created_at DATETIME DEFAULT CURRENT_TIMESTAMP ); CREATE INDEX IF NOT EXISTS idx_chains_chain_id ON chains(chain_id); "#; impl FaucetDatabase { /// Creates a new SQLite database connection. pub async fn new(database_path: &PathBuf) -> anyhow::Result<Self> { // Create parent directory if it doesn't exist. if let Some(parent) = database_path.parent() { tokio::fs::create_dir_all(parent) .await .context("Failed to create database directory")?; } let database_url = format!("sqlite:{}", database_path.display()); info!(?database_url, "Connecting to SQLite database"); let options = SqliteConnectOptions::new() .filename(database_path) .create_if_missing(true); let pool = SqlitePoolOptions::new() .max_connections(5) .connect_with(options) .await .context("Failed to connect to SQLite database")?; let db = Self { pool }; db.initialize_schema().await?; Ok(db) } /// Initializes the database schema. async fn initialize_schema(&self) -> anyhow::Result<()> { sqlx::query(CREATE_CHAINS_TABLE) .execute(&self.pool) .await .context("Failed to create chains table")?; info!("Database schema initialized"); Ok(()) } /// Synchronizes the database with the blockchain by traversing block history. pub async fn sync_with_blockchain<E>(&self, client: &ChainClient<E>) -> anyhow::Result<()> where E: linera_core::Environment, E::Storage: Storage, { info!("Starting database synchronization with blockchain"); // Build height->hash map and find sync point in a single traversal. let height_to_hash = self.build_sync_map(client).await?; info!( "Found sync point at height {}, processing {} blocks", height_to_hash.keys().next().unwrap_or(&BlockHeight::ZERO), height_to_hash.len() ); // Sync forward from the sync point using the pre-built map. self.sync_forward_with_map(client, height_to_hash).await?; info!("Database synchronization completed"); Ok(()) } /// Builds a height->hash map and finds the sync point in a single blockchain traversal. /// Returns (sync_point, height_to_hash_map). async fn build_sync_map<E>( &self, client: &ChainClient<E>, ) -> anyhow::Result<BTreeMap<BlockHeight, CryptoHash>> where E: linera_core::Environment, E::Storage: Storage, { let info = client.chain_info().await?; let end_height = info.next_block_height; if end_height == BlockHeight::ZERO { info!("Chain is empty, no synchronization needed"); return Ok(BTreeMap::new()); } let mut height_to_hash = BTreeMap::new(); let mut current_hash = info.block_hash; // Traverse backwards to build the height -> hash mapping and find sync point while let Some(hash) = current_hash { let certificate = client .storage_client() .read_certificate(hash) .await? .ok_or_else(|| anyhow::anyhow!("Certificate not found for hash {}", hash))?; let current_height = certificate.block().header.height; // Check if this block's chains are already in our database let chains_in_block = super::extract_opened_single_owner_chains(&certificate)?; if !chains_in_block.is_empty() { let mut all_chains_exist = true; for (owner, _description) in &chains_in_block { if self.get_chain_id(owner).await?.is_none() { all_chains_exist = false; break; } } if all_chains_exist { // All chains from this block are already in the database. break; } } // Add to our height->hash map height_to_hash.insert(current_height, hash); // Move to the previous block current_hash = certificate.block().header.previous_block_hash; } Ok(height_to_hash) } /// Syncs the database using a pre-built height->hash map. async fn sync_forward_with_map<E>( &self, client: &ChainClient<E>, height_to_hash: BTreeMap<BlockHeight, CryptoHash>, ) -> anyhow::Result<()> where E: linera_core::Environment, E::Storage: Storage, { if height_to_hash.is_empty() { return Ok(()); } // Process blocks in chronological order (forward) for (height, hash) in height_to_hash { let certificate = client .storage_client() .read_certificate(hash) .await? .ok_or_else(|| anyhow::anyhow!("Certificate not found for hash {}", hash))?; let chains_to_store = super::extract_opened_single_owner_chains(&certificate)? .into_iter() .map(|(owner, description)| (owner, description.id())) .collect::<Vec<_>>(); if !chains_to_store.is_empty() { info!( "Processing block at height {height} with {} new chains", chains_to_store.len() ); self.store_chains_batch(chains_to_store).await?; } } Ok(()) } /// Gets the chain ID for an owner if it exists. pub async fn get_chain_id(&self, owner: &AccountOwner) -> anyhow::Result<Option<ChainId>> { let owner_str = owner.to_string(); let Some(row) = sqlx::query("SELECT chain_id FROM chains WHERE owner = ?") .bind(&owner_str) .fetch_optional(&self.pool) .await? else { return Ok(None); }; let chain_id_str: String = row.get("chain_id"); let chain_id: ChainId = chain_id_str.parse()?; Ok(Some(chain_id)) } /// Stores multiple chain mappings in a single transaction pub async fn store_chains_batch( &self, chains: Vec<(AccountOwner, ChainId)>, ) -> anyhow::Result<()> { let mut tx = self.pool.begin().await?; for (owner, chain_id) in chains { let owner_str = owner.to_string(); let chain_id_str = chain_id.to_string(); sqlx::query( r#" INSERT OR REPLACE INTO chains (owner, chain_id) VALUES (?, ?) "#, ) .bind(&owner_str) .bind(&chain_id_str) .execute(&mut *tx) .await?; } tx.commit().await?; Ok(()) } }
rust
Apache-2.0
69f159d2106f7fc70870ce70074c55850bf1303b
2026-01-04T15:33:08.660695Z
false
linera-io/linera-protocol
https://github.com/linera-io/linera-protocol/blob/69f159d2106f7fc70870ce70074c55850bf1303b/linera-faucet/client/src/lib.rs
linera-faucet/client/src/lib.rs
// Copyright (c) Zefchain Labs, Inc. // SPDX-License-Identifier: Apache-2.0 //! The client component of the Linera faucet. // TODO(#3362): generate this code use std::collections::BTreeMap; use linera_base::{crypto::ValidatorPublicKey, data_types::ChainDescription}; use linera_client::config::GenesisConfig; use linera_execution::{committee::ValidatorState, Committee, ResourceControlPolicy}; use linera_version::VersionInfo; use thiserror_context::Context; #[derive(Debug, thiserror::Error)] #[non_exhaustive] pub enum ErrorInner { #[error("JSON parsing error: {0:?}")] Json(#[from] serde_json::Error), #[error("GraphQL error: {0:?}")] GraphQl(Vec<serde_json::Value>), #[error("HTTP error: {0:?}")] Http(#[from] reqwest::Error), } thiserror_context::impl_context!(Error(ErrorInner)); /// A faucet instance that can be queried. #[derive(Debug, Clone)] pub struct Faucet { url: String, } impl Faucet { pub fn new(url: String) -> Self { Self { url } } pub fn url(&self) -> &str { &self.url } async fn query<Response: serde::de::DeserializeOwned>( &self, query: impl AsRef<str>, ) -> Result<Response, Error> { let query = query.as_ref(); #[derive(serde::Deserialize)] struct GraphQlResponse<T> { data: Option<T>, errors: Option<Vec<serde_json::Value>>, } let builder = reqwest::ClientBuilder::new(); #[cfg(not(target_arch = "wasm32"))] let builder = builder.timeout(linera_base::time::Duration::from_secs(30)); let response: GraphQlResponse<Response> = builder .build() .unwrap() .post(&self.url) .json(&serde_json::json!({ "query": query, })) .send() .await .with_context(|| format!("executing query {query:?}"))? .error_for_status()? .json() .await?; if let Some(errors) = response.errors { // Extract just the error messages, ignore locations and path let messages = errors .iter() .filter_map(|error| { error .get("message") .and_then(|msg| msg.as_str()) .map(|s| s.to_string()) }) .collect::<Vec<_>>(); if messages.is_empty() { Err(ErrorInner::GraphQl(errors).into()) } else { Err( ErrorInner::GraphQl(vec![serde_json::Value::String(messages.join("; "))]) .into(), ) } } else { Ok(response .data .expect("no errors present but no data returned")) } } pub async fn genesis_config(&self) -> Result<GenesisConfig, Error> { #[derive(serde::Deserialize)] #[serde(rename_all = "camelCase")] struct Response { genesis_config: GenesisConfig, } Ok(self .query::<Response>("query { genesisConfig }") .await? .genesis_config) } pub async fn version_info(&self) -> Result<VersionInfo, Error> { #[derive(serde::Deserialize)] struct Response { version: VersionInfo, } Ok(self.query::<Response>("query { version }").await?.version) } pub async fn claim( &self, owner: &linera_base::identifiers::AccountOwner, ) -> Result<ChainDescription, Error> { #[derive(serde::Deserialize)] struct Response { claim: ChainDescription, } Ok(self .query::<Response>(format!("mutation {{ claim(owner: \"{owner}\") }}")) .await? .claim) } pub async fn current_validators(&self) -> Result<Vec<(ValidatorPublicKey, String)>, Error> { #[derive(serde::Deserialize)] #[serde(rename_all = "camelCase")] struct Validator { public_key: ValidatorPublicKey, network_address: String, } #[derive(serde::Deserialize)] #[serde(rename_all = "camelCase")] struct Response { current_validators: Vec<Validator>, } Ok(self .query::<Response>("query { currentValidators { publicKey networkAddress } }") .await? .current_validators .into_iter() .map(|validator| (validator.public_key, validator.network_address)) .collect()) } pub async fn current_committee(&self) -> Result<Committee, Error> { #[derive(serde::Deserialize)] struct CommitteeResponse { validators: BTreeMap<ValidatorPublicKey, ValidatorState>, policy: ResourceControlPolicy, } #[derive(serde::Deserialize)] #[serde(rename_all = "camelCase")] struct Response { current_committee: CommitteeResponse, } let response = self .query::<Response>( "query { currentCommittee { \ validators \ policy \ } }", ) .await?; let committee_response = response.current_committee; Ok(Committee::new( committee_response.validators, committee_response.policy, )) } }
rust
Apache-2.0
69f159d2106f7fc70870ce70074c55850bf1303b
2026-01-04T15:33:08.660695Z
false
linera-io/linera-protocol
https://github.com/linera-io/linera-protocol/blob/69f159d2106f7fc70870ce70074c55850bf1303b/linera-witty/build.rs
linera-witty/build.rs
// Copyright (c) Zefchain Labs, Inc. // SPDX-License-Identifier: Apache-2.0 fn main() { cfg_aliases::cfg_aliases! { with_log: { feature = "log" }, with_testing: { any(test, feature = "test") }, with_wasmer: { feature = "wasmer" }, with_wasmtime: { feature = "wasmtime" }, with_macros: { feature = "macros" }, with_wit_export: { all( feature = "macros", any(feature = "test", feature = "wasmer", feature = "wasmtime") ) }, } }
rust
Apache-2.0
69f159d2106f7fc70870ce70074c55850bf1303b
2026-01-04T15:33:08.660695Z
false
linera-io/linera-protocol
https://github.com/linera-io/linera-protocol/blob/69f159d2106f7fc70870ce70074c55850bf1303b/linera-witty/test-modules/src/reentrancy/global_state.rs
linera-witty/test-modules/src/reentrancy/global_state.rs
// Copyright (c) Zefchain Labs, Inc. // SPDX-License-Identifier: Apache-2.0 //! Helper Wasm module for reentrancy tests with a global state, to check that it is persisted //! across reentrant calls. #![cfg_attr(target_arch = "wasm32", no_main)] wit_bindgen::generate!("reentrant-global-state"); export_reentrant_global_state!(Implementation); use self::{ exports::witty_macros::test_modules::global_state::GlobalState, witty_macros::test_modules::get_host_value::*, }; static mut GLOBAL_STATE: u32 = 0; struct Implementation; impl GlobalState for Implementation { fn entrypoint(value: u32) -> u32 { unsafe { GLOBAL_STATE = value }; get_host_value() } fn get_global_state() -> u32 { unsafe { GLOBAL_STATE } } } #[cfg(not(target_arch = "wasm32"))] fn main() {}
rust
Apache-2.0
69f159d2106f7fc70870ce70074c55850bf1303b
2026-01-04T15:33:08.660695Z
false
linera-io/linera-protocol
https://github.com/linera-io/linera-protocol/blob/69f159d2106f7fc70870ce70074c55850bf1303b/linera-witty/test-modules/src/reentrancy/operations.rs
linera-witty/test-modules/src/reentrancy/operations.rs
// Copyright (c) Zefchain Labs, Inc. // SPDX-License-Identifier: Apache-2.0 //! Helper Wasm module for reentrancy tests with some functions that have multiple parameters and //! return values. #![cfg_attr(target_arch = "wasm32", no_main)] wit_bindgen::generate!("reentrant-operations"); export_reentrant_operations!(Implementation); use self::{ exports::witty_macros::test_modules::{entrypoint::Entrypoint, operations::Operations}, witty_macros::test_modules::operations::*, }; struct Implementation; impl Entrypoint for Implementation { #[expect(clippy::bool_assert_comparison)] fn entrypoint() { assert_eq!(and_bool(true, true), true); assert_eq!(and_bool(true, false), false); assert_eq!(add_s8(-100, 40), -60); assert_eq!(add_u8(201, 32), 233); assert_eq!(add_s16(-20_000, 30_000), 10_000); assert_eq!(add_u16(50_000, 256), 50_256); assert_eq!(add_s32(-2_000_000, -1), -2_000_001); assert_eq!(add_u32(4_000_000, 1), 4_000_001); assert_eq!(add_s64(-16_000_000, 32_000_000), 16_000_000); assert_eq!(add_u64(3_000_000_000, 9_345_678_999), 12_345_678_999); assert_eq!(add_float32(10.5, 120.25), 130.75); assert_eq!(add_float64(-0.000_08, 1.0), 0.999_92); } } impl Operations for Implementation { fn and_bool(first: bool, second: bool) -> bool { first && second } fn add_s8(first: i8, second: i8) -> i8 { first + second } fn add_u8(first: u8, second: u8) -> u8 { first + second } fn add_s16(first: i16, second: i16) -> i16 { first + second } fn add_u16(first: u16, second: u16) -> u16 { first + second } fn add_s32(first: i32, second: i32) -> i32 { first + second } fn add_u32(first: u32, second: u32) -> u32 { first + second } fn add_s64(first: i64, second: i64) -> i64 { first + second } fn add_u64(first: u64, second: u64) -> u64 { first + second } fn add_float32(first: f32, second: f32) -> f32 { first + second } fn add_float64(first: f64, second: f64) -> f64 { first + second } } #[cfg(not(target_arch = "wasm32"))] fn main() {}
rust
Apache-2.0
69f159d2106f7fc70870ce70074c55850bf1303b
2026-01-04T15:33:08.660695Z
false
linera-io/linera-protocol
https://github.com/linera-io/linera-protocol/blob/69f159d2106f7fc70870ce70074c55850bf1303b/linera-witty/test-modules/src/reentrancy/setters.rs
linera-witty/test-modules/src/reentrancy/setters.rs
// Copyright (c) Zefchain Labs, Inc. // SPDX-License-Identifier: Apache-2.0 //! Helper Wasm module for reentrancy tests with some functions that have one parameter and no //! return values. #![cfg_attr(target_arch = "wasm32", no_main)] wit_bindgen::generate!("reentrant-setters"); export_reentrant_setters!(Implementation); use self::{ exports::witty_macros::test_modules::{entrypoint::Entrypoint, setters::Setters}, witty_macros::test_modules::setters::*, }; struct Implementation; impl Entrypoint for Implementation { fn entrypoint() { set_bool(false); set_s8(-100); set_u8(201); set_s16(-20_000); set_u16(50_000); set_s32(-2_000_000); set_u32(4_000_000); set_float32(10.4); set_float64(-0.000_08); } } impl Setters for Implementation { #[expect(clippy::bool_assert_comparison)] fn set_bool(value: bool) { assert_eq!(value, false); } fn set_s8(value: i8) { assert_eq!(value, -100); } fn set_u8(value: u8) { assert_eq!(value, 201); } fn set_s16(value: i16) { assert_eq!(value, -20_000); } fn set_u16(value: u16) { assert_eq!(value, 50_000); } fn set_s32(value: i32) { assert_eq!(value, -2_000_000); } fn set_u32(value: u32) { assert_eq!(value, 4_000_000); } fn set_s64(value: i64) { assert_eq!(value, -25_000_000_000); } fn set_u64(value: u64) { assert_eq!(value, 7_000_000_000); } fn set_float32(value: f32) { assert_eq!(value, 10.4); } fn set_float64(value: f64) { assert_eq!(value, -0.000_08); } } #[cfg(not(target_arch = "wasm32"))] fn main() {}
rust
Apache-2.0
69f159d2106f7fc70870ce70074c55850bf1303b
2026-01-04T15:33:08.660695Z
false
linera-io/linera-protocol
https://github.com/linera-io/linera-protocol/blob/69f159d2106f7fc70870ce70074c55850bf1303b/linera-witty/test-modules/src/reentrancy/getters.rs
linera-witty/test-modules/src/reentrancy/getters.rs
// Copyright (c) Zefchain Labs, Inc. // SPDX-License-Identifier: Apache-2.0 //! Helper Wasm module for reentrancy tests with some functions that return values. #![cfg_attr(target_arch = "wasm32", no_main)] wit_bindgen::generate!("reentrant-getters"); export_reentrant_getters!(Implementation); use self::{ exports::witty_macros::test_modules::{entrypoint::Entrypoint, getters::Getters}, witty_macros::test_modules::getters::*, }; struct Implementation; impl Entrypoint for Implementation { #[expect(clippy::bool_assert_comparison)] fn entrypoint() { assert_eq!(get_true(), true); assert_eq!(get_false(), false); assert_eq!(get_s8(), -125); assert_eq!(get_u8(), 200); assert_eq!(get_s16(), -410); assert_eq!(get_u16(), 60_000); assert_eq!(get_s32(), -100_000); assert_eq!(get_u32(), 3_000_111); assert_eq!(get_s64(), -5_000_000); assert_eq!(get_u64(), 10_000_000_000); assert_eq!(get_float32(), -0.125); assert_eq!(get_float64(), 128.25); } } impl Getters for Implementation { fn get_true() -> bool { true } fn get_false() -> bool { false } fn get_s8() -> i8 { -125 } fn get_u8() -> u8 { 200 } fn get_s16() -> i16 { -410 } fn get_u16() -> u16 { 60_000 } fn get_s32() -> i32 { -100_000 } fn get_u32() -> u32 { 3_000_111 } fn get_s64() -> i64 { -5_000_000 } fn get_u64() -> u64 { 10_000_000_000 } fn get_float32() -> f32 { -0.125 } fn get_float64() -> f64 { 128.25 } } #[cfg(not(target_arch = "wasm32"))] fn main() {}
rust
Apache-2.0
69f159d2106f7fc70870ce70074c55850bf1303b
2026-01-04T15:33:08.660695Z
false
linera-io/linera-protocol
https://github.com/linera-io/linera-protocol/blob/69f159d2106f7fc70870ce70074c55850bf1303b/linera-witty/test-modules/src/reentrancy/simple_function.rs
linera-witty/test-modules/src/reentrancy/simple_function.rs
// Copyright (c) Zefchain Labs, Inc. // SPDX-License-Identifier: Apache-2.0 //! Helper Wasm module for reentrancy tests with a simple function that has no parameters nor //! returns values. #![cfg_attr(target_arch = "wasm32", no_main)] wit_bindgen::generate!("reentrant-simple-function"); export_reentrant_simple_function!(Implementation); use self::{ exports::witty_macros::test_modules::{ entrypoint::Entrypoint, simple_function::SimpleFunction, }, witty_macros::test_modules::simple_function::*, }; struct Implementation; impl Entrypoint for Implementation { fn entrypoint() { simple(); } } impl SimpleFunction for Implementation { fn simple() {} } #[cfg(not(target_arch = "wasm32"))] fn main() {}
rust
Apache-2.0
69f159d2106f7fc70870ce70074c55850bf1303b
2026-01-04T15:33:08.660695Z
false
linera-io/linera-protocol
https://github.com/linera-io/linera-protocol/blob/69f159d2106f7fc70870ce70074c55850bf1303b/linera-witty/test-modules/src/export/operations.rs
linera-witty/test-modules/src/export/operations.rs
// Copyright (c) Zefchain Labs, Inc. // SPDX-License-Identifier: Apache-2.0 //! Helper Wasm module with some functions that have two parameters and one return value. #![cfg_attr(target_arch = "wasm32", no_main)] wit_bindgen::generate!("export-operations"); export_export_operations!(Implementation); use self::exports::witty_macros::test_modules::operations::Operations; struct Implementation; impl Operations for Implementation { fn and_bool(first: bool, second: bool) -> bool { first && second } fn add_s8(first: i8, second: i8) -> i8 { first + second } fn add_u8(first: u8, second: u8) -> u8 { first + second } fn add_s16(first: i16, second: i16) -> i16 { first + second } fn add_u16(first: u16, second: u16) -> u16 { first + second } fn add_s32(first: i32, second: i32) -> i32 { first + second } fn add_u32(first: u32, second: u32) -> u32 { first + second } fn add_s64(first: i64, second: i64) -> i64 { first + second } fn add_u64(first: u64, second: u64) -> u64 { first + second } fn add_float32(first: f32, second: f32) -> f32 { first + second } fn add_float64(first: f64, second: f64) -> f64 { first + second } } #[cfg(not(target_arch = "wasm32"))] fn main() {}
rust
Apache-2.0
69f159d2106f7fc70870ce70074c55850bf1303b
2026-01-04T15:33:08.660695Z
false
linera-io/linera-protocol
https://github.com/linera-io/linera-protocol/blob/69f159d2106f7fc70870ce70074c55850bf1303b/linera-witty/test-modules/src/export/setters.rs
linera-witty/test-modules/src/export/setters.rs
// Copyright (c) Zefchain Labs, Inc. // SPDX-License-Identifier: Apache-2.0 //! Helper Wasm module with some functions that have one parameter and no return values. #![cfg_attr(target_arch = "wasm32", no_main)] wit_bindgen::generate!("export-setters"); export_export_setters!(Implementation); use self::exports::witty_macros::test_modules::setters::Setters; struct Implementation; impl Setters for Implementation { #[expect(clippy::bool_assert_comparison)] fn set_bool(value: bool) { assert_eq!(value, false); } fn set_s8(value: i8) { assert_eq!(value, -100); } fn set_u8(value: u8) { assert_eq!(value, 201); } fn set_s16(value: i16) { assert_eq!(value, -20_000); } fn set_u16(value: u16) { assert_eq!(value, 50_000); } fn set_s32(value: i32) { assert_eq!(value, -2_000_000); } fn set_u32(value: u32) { assert_eq!(value, 4_000_000); } fn set_s64(value: i64) { assert_eq!(value, -25_000_000_000); } fn set_u64(value: u64) { assert_eq!(value, 7_000_000_000); } fn set_float32(value: f32) { assert_eq!(value, 10.4); } fn set_float64(value: f64) { assert_eq!(value, -0.000_08); } } #[cfg(not(target_arch = "wasm32"))] fn main() {}
rust
Apache-2.0
69f159d2106f7fc70870ce70074c55850bf1303b
2026-01-04T15:33:08.660695Z
false
linera-io/linera-protocol
https://github.com/linera-io/linera-protocol/blob/69f159d2106f7fc70870ce70074c55850bf1303b/linera-witty/test-modules/src/export/getters.rs
linera-witty/test-modules/src/export/getters.rs
// Copyright (c) Zefchain Labs, Inc. // SPDX-License-Identifier: Apache-2.0 //! Helper Wasm module with some functions that have no parameters but return values. #![cfg_attr(target_arch = "wasm32", no_main)] wit_bindgen::generate!("export-getters"); export_export_getters!(Implementation); use self::exports::witty_macros::test_modules::getters::Getters; struct Implementation; impl Getters for Implementation { fn get_true() -> bool { true } fn get_false() -> bool { false } fn get_s8() -> i8 { -125 } fn get_u8() -> u8 { 200 } fn get_s16() -> i16 { -410 } fn get_u16() -> u16 { 60_000 } fn get_s32() -> i32 { -100_000 } fn get_u32() -> u32 { 3_000_111 } fn get_s64() -> i64 { -5_000_000 } fn get_u64() -> u64 { 10_000_000_000 } fn get_float32() -> f32 { -0.125 } fn get_float64() -> f64 { 128.25 } } #[cfg(not(target_arch = "wasm32"))] fn main() {}
rust
Apache-2.0
69f159d2106f7fc70870ce70074c55850bf1303b
2026-01-04T15:33:08.660695Z
false
linera-io/linera-protocol
https://github.com/linera-io/linera-protocol/blob/69f159d2106f7fc70870ce70074c55850bf1303b/linera-witty/test-modules/src/export/simple_function.rs
linera-witty/test-modules/src/export/simple_function.rs
// Copyright (c) Zefchain Labs, Inc. // SPDX-License-Identifier: Apache-2.0 //! Helper Wasm module with a minimal function without parameters or return values. #![cfg_attr(target_arch = "wasm32", no_main)] wit_bindgen::generate!("export-simple-function"); export_export_simple_function!(Implementation); use self::exports::witty_macros::test_modules::simple_function::SimpleFunction; struct Implementation; impl SimpleFunction for Implementation { fn simple() {} } #[cfg(not(target_arch = "wasm32"))] fn main() {}
rust
Apache-2.0
69f159d2106f7fc70870ce70074c55850bf1303b
2026-01-04T15:33:08.660695Z
false