Skip to content

Commit

Permalink
Support non-zero base AssetId (#71)
Browse files Browse the repository at this point in the history
  • Loading branch information
xgreenx authored May 3, 2024
1 parent 01232ce commit c6abfd8
Show file tree
Hide file tree
Showing 5 changed files with 35 additions and 23 deletions.
7 changes: 2 additions & 5 deletions src/config.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,9 @@
use crate::constants::{
CAPTCHA_KEY, CAPTCHA_SECRET, DEFAULT_DISPENSE_INTERVAL, DEFAULT_FAUCET_DISPENSE_AMOUNT,
DEFAULT_NODE_URL, DEFAULT_PORT, DISPENSE_AMOUNT, DISPENSE_INTERVAL, FAUCET_ASSET_ID,
FUEL_NODE_URL, HUMAN_LOGGING, LOG_FILTER, PUBLIC_FUEL_NODE_URL, SERVICE_PORT, TIMEOUT_SECONDS,
DEFAULT_NODE_URL, DEFAULT_PORT, DISPENSE_AMOUNT, DISPENSE_INTERVAL, FUEL_NODE_URL,
HUMAN_LOGGING, LOG_FILTER, PUBLIC_FUEL_NODE_URL, SERVICE_PORT, TIMEOUT_SECONDS,
WALLET_SECRET_KEY,
};
use fuels_core::types::AssetId;
use secrecy::Secret;
use std::env;

Expand All @@ -19,7 +18,6 @@ pub struct Config {
pub public_node_url: String,
pub wallet_secret_key: Option<Secret<String>>,
pub dispense_amount: u64,
pub dispense_asset_id: AssetId,
pub dispense_limit_interval: u64,
pub timeout: u64,
}
Expand All @@ -44,7 +42,6 @@ impl Default for Config {
.unwrap_or_else(|_| DEFAULT_FAUCET_DISPENSE_AMOUNT.to_string())
.parse::<u64>()
.expect("expected a valid integer for DISPENSE_AMOUNT"),
dispense_asset_id: FAUCET_ASSET_ID,
dispense_limit_interval: env::var(DISPENSE_INTERVAL)
.unwrap_or_else(|_| DEFAULT_DISPENSE_INTERVAL.to_string())
.parse::<u64>()
Expand Down
3 changes: 0 additions & 3 deletions src/constants.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
use fuels_core::types::AssetId;

pub const LOG_FILTER: &str = "RUST_LOG";
pub const HUMAN_LOGGING: &str = "HUMAN_LOGGING";
pub const CAPTCHA_KEY: &str = "CAPTCHA_KEY";
Expand All @@ -14,7 +12,6 @@ pub const DISPENSE_AMOUNT: &str = "DISPENSE_AMOUNT";
pub const DISPENSE_INTERVAL: &str = "DISPENSE_LIMIT_INTERVAL";
pub const DEFAULT_DISPENSE_INTERVAL: u64 = 24 * 60 * 60;
pub const DEFAULT_FAUCET_DISPENSE_AMOUNT: u64 = 10_000_000;
pub const FAUCET_ASSET_ID: AssetId = AssetId::new([0; 32]);
pub const SERVICE_PORT: &str = "PORT";
pub const DEFAULT_PORT: u16 = 3000;

Expand Down
3 changes: 2 additions & 1 deletion src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,7 @@ pub async fn start_server(
let provider = Provider::connect(service_config.node_url.clone())
.await
.expect("Should create a provider");
let base_asset_id = *provider.consensus_parameters().base_asset_id();

// setup wallet
let secret = service_config
Expand All @@ -112,7 +113,7 @@ pub async fn start_server(
);

let balance = wallet
.get_coins(service_config.dispense_asset_id)
.get_coins(base_asset_id)
.await
.expect("Failed to fetch initial balance from fuel core")
.into_iter()
Expand Down
27 changes: 18 additions & 9 deletions src/routes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -146,9 +146,13 @@ fn check_and_mark_dispense_limit(
Ok(())
}

async fn get_coins(wallet: &WalletUnlocked, amount: u64) -> Result<Vec<Input>, DispenseError> {
async fn get_coins(
wallet: &WalletUnlocked,
base_asset_id: &AssetId,
amount: u64,
) -> Result<Vec<Input>, DispenseError> {
wallet
.get_spendable_resources(AssetId::BASE, amount)
.get_spendable_resources(*base_asset_id, amount)
.await
.map_err(|e| {
error(
Expand Down Expand Up @@ -245,6 +249,7 @@ pub async fn dispense_tokens(
});

let provider = wallet.provider().expect("client provider");
let base_asset_id = *provider.consensus_parameters().base_asset_id();

let mut tx_id = None;
for _ in 0..5 {
Expand All @@ -253,25 +258,25 @@ pub async fn dispense_tokens(
let coin_type = CoinType::Coin(Coin {
amount: previous_coin_output.amount,
block_created: 0u32,
asset_id: config.dispense_asset_id,
asset_id: base_asset_id,
utxo_id: previous_coin_output.utxo_id,
owner: previous_coin_output.owner.into(),
status: CoinStatus::Unspent,
});

vec![Input::resource_signed(coin_type)]
} else {
get_coins(&wallet, config.dispense_amount).await?
get_coins(&wallet, &base_asset_id, config.dispense_amount).await?
};

let mut outputs = wallet.get_asset_outputs_for_amount(
&address.into(),
config.dispense_asset_id,
base_asset_id,
config.dispense_amount,
);
let faucet_address: Address = wallet.address().into();
// Add an additional output to store the stable part of the fee change.
outputs.push(Output::coin(faucet_address, 0, config.dispense_asset_id));
outputs.push(Output::coin(faucet_address, 0, base_asset_id));

let tip = guard.next_tip();

Expand Down Expand Up @@ -307,7 +312,7 @@ pub async fn dispense_tokens(
"Overflow during calculating `TransactionFee`".to_string(),
StatusCode::INTERNAL_SERVER_ERROR,
))?;
let available_balance = available_balance(&tx_builder.inputs, &config.dispense_asset_id);
let available_balance = available_balance(&tx_builder.inputs, &base_asset_id);
let stable_fee_change = available_balance
.checked_sub(fee.max_fee().saturating_add(config.dispense_amount))
.ok_or(error(
Expand All @@ -316,7 +321,7 @@ pub async fn dispense_tokens(
))?;

*tx_builder.outputs.last_mut().unwrap() =
Output::coin(faucet_address, stable_fee_change, config.dispense_asset_id);
Output::coin(faucet_address, stable_fee_change, base_asset_id);

let script = tx_builder.build(provider).await.expect("Valid script");

Expand Down Expand Up @@ -388,10 +393,14 @@ pub async fn dispense_tokens(
#[tracing::instrument(skip_all)]
pub async fn dispense_info(
Extension(config): Extension<SharedConfig>,
Extension(wallet): Extension<SharedWallet>,
) -> Result<DispenseInfoResponse, DispenseError> {
let provider = wallet.provider().expect("client provider");
let base_asset_id = *provider.consensus_parameters().base_asset_id();

Ok(DispenseInfoResponse {
amount: config.dispense_amount,
asset_id: config.dispense_asset_id.to_string(),
asset_id: base_asset_id.to_string(),
})
}

Expand Down
18 changes: 13 additions & 5 deletions tests/dispense.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ use fuel_faucet::config::Config;
use fuel_faucet::models::DispenseInfoResponse;
use fuel_faucet::{start_server, Clock, THE_BIGGEST_AMOUNT};
use fuel_tx::ConsensusParameters;
use fuel_types::{Address, AssetId};
use fuel_types::Address;
use fuels_accounts::provider::Provider;
use fuels_accounts::wallet::WalletUnlocked;
use fuels_core::types::bech32::Bech32Address;
Expand Down Expand Up @@ -60,6 +60,7 @@ impl TestContext {
let dispense_amount = rng.gen_range(1..10000u64);
let secret_key: SecretKey = SecretKey::random(&mut rng);
let wallet = WalletUnlocked::new_from_private_key(secret_key, None);
let base_asset_id = [1; 32].into();

let mut generator = CoinConfigGenerator::new();
let mut coins: Vec<_> = (0..10000)
Expand All @@ -77,7 +78,7 @@ impl TestContext {
coins.push(CoinConfig {
owner: wallet.address().into(),
amount: 1 << 50,
asset_id: Default::default(),
asset_id: base_asset_id,
..generator.generate()
});

Expand All @@ -89,6 +90,7 @@ impl TestContext {
let mut consensus_parameters = ConsensusParameters::default();
consensus_parameters
.set_fee_params(fuel_tx::FeeParameters::default().with_gas_price_factor(1));
consensus_parameters.set_base_asset_id(base_asset_id);

let chain_config = ChainConfig {
consensus_parameters,
Expand Down Expand Up @@ -121,7 +123,6 @@ impl TestContext {
node_url: format!("http://{}", fuel_node.bound_address),
wallet_secret_key: Some(Secret::new(format!("{secret_key:x}"))),
dispense_amount,
dispense_asset_id: AssetId::default(),
..Default::default()
};

Expand Down Expand Up @@ -157,7 +158,11 @@ async fn can_start_server() {
assert_eq!(response.amount, context.faucet_config.dispense_amount);
assert_eq!(
response.asset_id,
context.faucet_config.dispense_asset_id.to_string()
context
.provider
.consensus_parameters()
.base_asset_id()
.to_string()
);
}

Expand Down Expand Up @@ -208,7 +213,10 @@ async fn _dispense_sends_coins_to_valid_address(

let test_balance: u64 = context
.provider
.get_coins(&recipient_address, context.faucet_config.dispense_asset_id)
.get_coins(
&recipient_address,
*context.provider.consensus_parameters().base_asset_id(),
)
.await
.unwrap()
.iter()
Expand Down

0 comments on commit c6abfd8

Please sign in to comment.