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 |
|---|---|---|---|---|---|---|---|---|
FuelLabs/fuels-rs | https://github.com/FuelLabs/fuels-rs/blob/865e00c295de8b4a0a1ef7ac926c3c8266d5151b/packages/fuels-core/src/types/dry_runner.rs | packages/fuels-core/src/types/dry_runner.rs | use std::fmt::Debug;
use async_trait::async_trait;
use fuel_tx::{ConsensusParameters, Transaction as FuelTransaction};
use crate::types::errors::Result;
#[derive(Debug, Clone, Copy)]
pub struct DryRun {
pub succeeded: bool,
pub script_gas: u64,
pub variable_outputs: usize,
}
impl DryRun {
pub fn gas_with_tolerance(&self, tolerance: f32) -> u64 {
let gas_used = self.script_gas as f64;
let adjusted_gas = gas_used * (1.0 + f64::from(tolerance));
adjusted_gas.ceil() as u64
}
}
#[cfg_attr(target_arch = "wasm32", async_trait(?Send))]
#[cfg_attr(not(target_arch = "wasm32"), async_trait)]
pub trait DryRunner: Send + Sync {
async fn dry_run(&self, tx: FuelTransaction) -> Result<DryRun>;
async fn estimate_gas_price(&self, block_horizon: u32) -> Result<u64>;
async fn consensus_parameters(&self) -> Result<ConsensusParameters>;
async fn estimate_predicates(
&self,
tx: &FuelTransaction,
latest_chain_executor_version: Option<u32>,
) -> Result<FuelTransaction>;
}
#[cfg_attr(target_arch = "wasm32", async_trait(?Send))]
#[cfg_attr(not(target_arch = "wasm32"), async_trait)]
impl<T: DryRunner> DryRunner for &T {
async fn dry_run(&self, tx: FuelTransaction) -> Result<DryRun> {
(*self).dry_run(tx).await
}
async fn estimate_gas_price(&self, block_horizon: u32) -> Result<u64> {
(*self).estimate_gas_price(block_horizon).await
}
async fn consensus_parameters(&self) -> Result<ConsensusParameters> {
(*self).consensus_parameters().await
}
async fn estimate_predicates(
&self,
tx: &FuelTransaction,
latest_chain_executor_version: Option<u32>,
) -> Result<FuelTransaction> {
(*self)
.estimate_predicates(tx, latest_chain_executor_version)
.await
}
}
| rust | Apache-2.0 | 865e00c295de8b4a0a1ef7ac926c3c8266d5151b | 2026-01-04T15:31:59.450823Z | false |
FuelLabs/fuels-rs | https://github.com/FuelLabs/fuels-rs/blob/865e00c295de8b4a0a1ef7ac926c3c8266d5151b/packages/fuels-core/src/types/wrappers.rs | packages/fuels-core/src/types/wrappers.rs | pub mod block;
pub mod chain_info;
pub mod coin;
pub mod coin_type;
pub mod coin_type_id;
pub mod input;
pub mod message;
pub mod message_proof;
pub mod node_info;
pub mod transaction;
pub mod transaction_response;
pub mod output {
pub use fuel_tx::Output;
}
#[cfg(feature = "std")]
pub mod gas_price {
pub use fuel_core_client::client::types::gas_price::{EstimateGasPrice, LatestGasPrice};
}
| rust | Apache-2.0 | 865e00c295de8b4a0a1ef7ac926c3c8266d5151b | 2026-01-04T15:31:59.450823Z | false |
FuelLabs/fuels-rs | https://github.com/FuelLabs/fuels-rs/blob/865e00c295de8b4a0a1ef7ac926c3c8266d5151b/packages/fuels-core/src/types/checksum_address.rs | packages/fuels-core/src/types/checksum_address.rs | use sha2::{Digest, Sha256};
use crate::types::errors::{Error, Result};
pub fn checksum_encode(address: &str) -> Result<String> {
let trimmed = address.trim_start_matches("0x");
pre_validate(trimmed)?;
let lowercase = trimmed.to_ascii_lowercase();
let hash = Sha256::digest(lowercase.as_bytes());
let mut checksum = String::with_capacity(trimmed.len());
for (i, addr_char) in lowercase.chars().enumerate() {
let hash_byte = hash[i / 2];
let hash_nibble = if i % 2 == 0 {
// even index: high nibble
(hash_byte >> 4) & 0x0F
} else {
// odd index: low nibble
hash_byte & 0x0F
};
// checksum rule
if hash_nibble > 7 {
checksum.push(addr_char.to_ascii_uppercase());
} else {
checksum.push(addr_char);
}
}
Ok(format!("0x{checksum}"))
}
fn pre_validate(s: &str) -> Result<()> {
if s.len() != 64 {
return Err(Error::Codec("invalid address length".to_string()));
}
if !s.chars().all(|c| c.is_ascii_hexdigit()) {
return Err(Error::Codec(
"address contains invalid characters".to_string(),
));
}
Ok(())
}
pub fn is_checksum_valid(address: &str) -> bool {
let Ok(checksum) = checksum_encode(address) else {
return false;
};
let address_normalized = if address.starts_with("0x") {
address.to_string()
} else {
format!("0x{}", address)
};
checksum == address_normalized
}
#[cfg(test)]
mod test {
use std::str::FromStr;
use fuel_core_client::client::schema::Address;
use super::*;
const VALID_CHECKSUM: [&str; 4] = [
"0x9cfB2CAd509D417ec40b70ebE1DD72a3624D46fdD1Ea5420dBD755CE7f4Dc897",
"0x54944e5B8189827e470e5a8bAcFC6C3667397DC4E1EEF7EF3519d16D6D6c6610",
"c36bE0E14d3EAf5d8D233e0F4a40b3b4e48427D25F84C460d2B03B242A38479e",
"a1184D77D0D08A064E03b2bd9f50863e88faDdea4693A05cA1ee9B1732ea99B7",
];
const INVALID_CHECKSUM: [&str; 8] = [
"0x587aa0482482efEa0234752d1ad9a9c438D1f34D2859b8bef2d56A432cB68e33",
"0xe10f526B192593793b7a1559aA91445faba82a1d669e3eb2DCd17f9c121b24b1",
"6b63804cFbF9856e68e5B6e7aEf238dc8311ec55bec04df774003A2c96E0418e",
"81f3A10b61828580D06cC4c7b0ed8f59b9Fb618bE856c55d33deCD95489A1e23",
// all lower
"0xf8f8b6283d7fa5b672b530cbb84fcccb4ff8dc40f8176ef4544ddb1f1952ad07",
"7e2becd64cd598da59b4d1064b711661898656c6b1f4918a787156b8965dc83c",
// all caps
"0x26183FBE7375045250865947695DFC12500DCC43EFB9102B4E8C4D3C20009DCB",
"577E424EE53A16E6A85291FEABC8443862495F74AC39A706D2DD0B9FC16955EB",
];
const INVALID_LEN: [&str; 6] = [
// too short
"0x1234567890abcdef",
// too long
"0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef1234",
// 65 characters
"1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef1",
// 63 characters
"0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcde",
"",
"0x",
];
const INVALID_CHARACTERS: &str =
"0xGHIJKL7890abcdef1234567890abcdef1234567890abcdef1234567890abcdef";
#[test]
fn will_detect_valid_checksums() {
for valid in VALID_CHECKSUM.iter() {
assert!(is_checksum_valid(valid));
}
}
#[test]
fn will_detect_invalid_checksums() {
for invalid in INVALID_CHECKSUM.iter() {
assert!(!is_checksum_valid(invalid));
}
}
#[test]
fn can_construct_address_from_checksum() {
let checksum = checksum_encode(INVALID_CHECKSUM[0]).expect("should encode");
Address::from_str(&checksum).expect("should be valid address");
}
#[test]
fn will_detect_invalid_lengths() {
for invalid in INVALID_LEN.iter() {
let result = checksum_encode(invalid).expect_err("should not encode");
assert!(result.to_string().contains("invalid address length"));
}
}
#[test]
fn will_detect_invalid_characters() {
let result = checksum_encode(INVALID_CHARACTERS).expect_err("should not encode");
assert!(
result
.to_string()
.contains("address contains invalid characters")
);
}
}
| rust | Apache-2.0 | 865e00c295de8b4a0a1ef7ac926c3c8266d5151b | 2026-01-04T15:31:59.450823Z | false |
FuelLabs/fuels-rs | https://github.com/FuelLabs/fuels-rs/blob/865e00c295de8b4a0a1ef7ac926c3c8266d5151b/packages/fuels-core/src/types/method_descriptor.rs | packages/fuels-core/src/types/method_descriptor.rs | /// This type is used to specify the fn_selector and name
/// of methods on contracts at compile time, exported by the abigen! macro
#[derive(Debug, Clone, Copy)]
pub struct MethodDescriptor {
/// The name of the method.
pub name: &'static str,
/// The function selector of the method.
pub fn_selector: &'static [u8],
}
impl MethodDescriptor {
/// Returns the function selector of the method.
pub const fn fn_selector(&self) -> &'static [u8] {
self.fn_selector
}
/// Returns the name of the method.
pub const fn name(&self) -> &'static str {
self.name
}
}
| rust | Apache-2.0 | 865e00c295de8b4a0a1ef7ac926c3c8266d5151b | 2026-01-04T15:31:59.450823Z | false |
FuelLabs/fuels-rs | https://github.com/FuelLabs/fuels-rs/blob/865e00c295de8b4a0a1ef7ac926c3c8266d5151b/packages/fuels-core/src/types/core.rs | packages/fuels-core/src/types/core.rs | pub use bits::*;
pub use bytes::*;
pub use identity::*;
pub use raw_slice::*;
pub use sized_ascii_string::*;
pub use u256::*;
mod bits;
mod bytes;
mod identity;
mod raw_slice;
mod sized_ascii_string;
mod u256;
| rust | Apache-2.0 | 865e00c295de8b4a0a1ef7ac926c3c8266d5151b | 2026-01-04T15:31:59.450823Z | false |
FuelLabs/fuels-rs | https://github.com/FuelLabs/fuels-rs/blob/865e00c295de8b4a0a1ef7ac926c3c8266d5151b/packages/fuels-core/src/types/tx_response.rs | packages/fuels-core/src/types/tx_response.rs | use fuel_tx::TxId;
use super::tx_status::Success;
#[derive(Clone, Debug)]
pub struct TxResponse {
pub tx_status: Success,
pub tx_id: TxId,
}
| rust | Apache-2.0 | 865e00c295de8b4a0a1ef7ac926c3c8266d5151b | 2026-01-04T15:31:59.450823Z | false |
FuelLabs/fuels-rs | https://github.com/FuelLabs/fuels-rs/blob/865e00c295de8b4a0a1ef7ac926c3c8266d5151b/packages/fuels-core/src/types/tx_status.rs | packages/fuels-core/src/types/tx_status.rs | use fuel_abi_types::error_codes::{
FAILED_ASSERT_EQ_SIGNAL, FAILED_ASSERT_NE_SIGNAL, FAILED_ASSERT_SIGNAL, FAILED_REQUIRE_SIGNAL,
FAILED_SEND_MESSAGE_SIGNAL, FAILED_TRANSFER_TO_ADDRESS_SIGNAL, REVERT_WITH_LOG_SIGNAL,
};
#[cfg(feature = "std")]
use fuel_core_client::client::types::TransactionStatus as ClientTransactionStatus;
#[cfg(feature = "std")]
use fuel_core_types::services::executor::{TransactionExecutionResult, TransactionExecutionStatus};
use fuel_tx::Receipt;
#[cfg(feature = "std")]
use fuel_vm::state::ProgramState;
#[cfg(feature = "std")]
use std::sync::Arc;
#[cfg(not(feature = "std"))]
use alloc::sync::Arc;
use crate::{
codec::LogDecoder,
types::errors::{Error, Result, transaction::Reason},
};
#[derive(Debug, Clone)]
pub struct Success {
pub receipts: Arc<Vec<Receipt>>,
pub total_fee: u64,
pub total_gas: u64,
}
#[derive(Debug, Clone)]
pub struct SqueezedOut {
pub reason: String,
}
#[derive(Debug, Clone)]
pub struct Failure {
pub reason: String,
pub receipts: Arc<Vec<Receipt>>,
pub revert_id: Option<u64>,
pub total_fee: u64,
pub total_gas: u64,
}
#[derive(Debug, Clone)]
pub enum TxStatus {
Success(Success),
PreconfirmationSuccess(Success),
Submitted,
SqueezedOut(SqueezedOut),
Failure(Failure),
PreconfirmationFailure(Failure),
}
impl TxStatus {
pub fn check(&self, log_decoder: Option<&LogDecoder>) -> Result<()> {
match self {
Self::SqueezedOut(SqueezedOut { reason }) => {
Err(Error::Transaction(Reason::SqueezedOut(reason.clone())))
}
Self::Failure(Failure {
receipts,
reason,
revert_id,
..
}) => Err(Self::map_revert_error(
receipts.clone(),
reason,
*revert_id,
log_decoder,
)),
_ => Ok(()),
}
}
pub fn take_success_checked(self, log_decoder: Option<&LogDecoder>) -> Result<Success> {
match self {
Self::SqueezedOut(SqueezedOut { reason }) => {
Err(Error::Transaction(Reason::SqueezedOut(reason.clone())))
}
Self::Failure(Failure {
receipts,
reason,
revert_id,
..
})
| Self::PreconfirmationFailure(Failure {
receipts,
reason,
revert_id,
..
}) => Err(Self::map_revert_error(
receipts,
&reason,
revert_id,
log_decoder,
)),
Self::Submitted => Err(Error::Transaction(Reason::Other(
"transactions was not yet included".to_owned(),
))),
Self::Success(success) | Self::PreconfirmationSuccess(success) => Ok(success),
}
}
pub fn total_gas(&self) -> u64 {
match self {
TxStatus::Success(Success { total_gas, .. })
| TxStatus::Failure(Failure { total_gas, .. }) => *total_gas,
_ => 0,
}
}
pub fn total_fee(&self) -> u64 {
match self {
TxStatus::Success(Success { total_fee, .. })
| TxStatus::Failure(Failure { total_fee, .. }) => *total_fee,
_ => 0,
}
}
fn map_revert_error(
receipts: Arc<Vec<Receipt>>,
reason: &str,
revert_id: Option<u64>,
log_decoder: Option<&LogDecoder>,
) -> Error {
if let (Some(revert_id), Some(log_decoder)) = (revert_id, log_decoder)
&& let Some(error_detail) = log_decoder.get_error_codes(&revert_id)
{
let error_message = if error_detail.log_id.is_some() {
log_decoder
.decode_last_log(&receipts)
.unwrap_or_else(|err| {
format!("failed to decode log from require revert: {err}")
})
} else {
error_detail.msg.clone().expect("is there")
};
let reason = format!(
"panicked at: `{}` - `{}:{}:{}` with message `{}`",
error_detail.pkg,
error_detail.file,
error_detail.line,
error_detail.column,
error_message
);
return Error::Transaction(Reason::Failure {
reason,
revert_id: Some(revert_id),
receipts,
});
}
let reason = match (revert_id, log_decoder) {
(Some(FAILED_REQUIRE_SIGNAL), Some(log_decoder)) => log_decoder
.decode_last_log(&receipts)
.unwrap_or_else(|err| format!("failed to decode log from require revert: {err}")),
(Some(REVERT_WITH_LOG_SIGNAL), Some(log_decoder)) => log_decoder
.decode_last_log(&receipts)
.unwrap_or_else(|err| format!("failed to decode log from revert_with_log: {err}")),
(Some(FAILED_ASSERT_EQ_SIGNAL), Some(log_decoder)) => {
match log_decoder.decode_last_two_logs(&receipts) {
Ok((lhs, rhs)) => format!(
"assertion failed: `(left == right)`\n left: `{lhs:?}`\n right: `{rhs:?}`"
),
Err(err) => {
format!("failed to decode log from assert_eq revert: {err}")
}
}
}
(Some(FAILED_ASSERT_NE_SIGNAL), Some(log_decoder)) => {
match log_decoder.decode_last_two_logs(&receipts) {
Ok((lhs, rhs)) => format!(
"assertion failed: `(left != right)`\n left: `{lhs:?}`\n right: `{rhs:?}`"
),
Err(err) => {
format!("failed to decode log from assert_eq revert: {err}")
}
}
}
(Some(FAILED_ASSERT_SIGNAL), _) => "assertion failed".into(),
(Some(FAILED_SEND_MESSAGE_SIGNAL), _) => "failed to send message".into(),
(Some(FAILED_TRANSFER_TO_ADDRESS_SIGNAL), _) => "failed transfer to address".into(),
_ => reason.to_string(),
};
Error::Transaction(Reason::Failure {
reason,
revert_id,
receipts,
})
}
pub fn take_receipts_checked(
self,
log_decoder: Option<&LogDecoder>,
) -> Result<Arc<Vec<Receipt>>> {
self.check(log_decoder)?;
Ok(self.take_receipts())
}
pub fn take_receipts(self) -> Arc<Vec<Receipt>> {
match self {
TxStatus::Success(Success { receipts, .. })
| TxStatus::Failure(Failure { receipts, .. }) => receipts,
_ => Default::default(),
}
}
pub fn is_final(&self) -> bool {
matches!(
self,
TxStatus::Success(_) | TxStatus::Failure(_) | TxStatus::SqueezedOut(_)
)
}
}
#[cfg(feature = "std")]
impl From<ClientTransactionStatus> for TxStatus {
fn from(client_status: ClientTransactionStatus) -> Self {
match client_status {
ClientTransactionStatus::Submitted { .. } => TxStatus::Submitted {},
ClientTransactionStatus::Success {
receipts,
total_gas,
total_fee,
..
} => TxStatus::Success(Success {
receipts: receipts.into(),
total_gas,
total_fee,
}),
ClientTransactionStatus::PreconfirmationSuccess {
receipts,
total_gas,
total_fee,
..
} => TxStatus::PreconfirmationSuccess(Success {
receipts: receipts.unwrap_or_default().into(),
total_gas,
total_fee,
}),
ClientTransactionStatus::Failure {
reason,
program_state,
receipts,
total_gas,
total_fee,
..
} => {
let revert_id = program_state.and_then(|state| match state {
ProgramState::Revert(revert_id) => Some(revert_id),
_ => None,
});
TxStatus::Failure(Failure {
receipts: receipts.into(),
reason,
revert_id,
total_gas,
total_fee,
})
}
ClientTransactionStatus::PreconfirmationFailure {
reason,
receipts,
total_gas,
total_fee,
..
} => TxStatus::Failure(Failure {
receipts: receipts.unwrap_or_default().into(),
reason,
revert_id: None,
total_gas,
total_fee,
}),
ClientTransactionStatus::SqueezedOut { reason } => {
TxStatus::SqueezedOut(SqueezedOut { reason })
}
}
}
}
#[cfg(feature = "std")]
impl From<TransactionExecutionStatus> for TxStatus {
fn from(value: TransactionExecutionStatus) -> Self {
match value.result {
TransactionExecutionResult::Success {
receipts,
total_gas,
total_fee,
..
} => Self::Success(Success {
receipts,
total_gas,
total_fee,
}),
TransactionExecutionResult::Failed {
result,
receipts,
total_gas,
total_fee,
..
} => {
let revert_id = result.and_then(|result| match result {
ProgramState::Revert(revert_id) => Some(revert_id),
_ => None,
});
let reason = TransactionExecutionResult::reason(&receipts, &result);
Self::Failure(Failure {
receipts,
reason,
revert_id,
total_gas,
total_fee,
})
}
}
}
}
| rust | Apache-2.0 | 865e00c295de8b4a0a1ef7ac926c3c8266d5151b | 2026-01-04T15:31:59.450823Z | false |
FuelLabs/fuels-rs | https://github.com/FuelLabs/fuels-rs/blob/865e00c295de8b4a0a1ef7ac926c3c8266d5151b/packages/fuels-core/src/types/transaction_builders.rs | packages/fuels-core/src/types/transaction_builders.rs | #![cfg(feature = "std")]
use async_trait::async_trait;
use fuel_asm::{GTFArgs, RegId, op};
use fuel_crypto::{Hasher, Message as CryptoMessage, Signature};
use fuel_tx::{
Chargeable, ConsensusParameters, Create, Input as FuelInput, Output, Script, StorageSlot,
Transaction as FuelTransaction, TransactionFee, TxPointer, UniqueIdentifier, Upgrade, Upload,
UploadBody, Witness,
field::{Outputs, Policies as PoliciesField, ScriptGasLimit, Witnesses},
policies::{Policies, PolicyType},
};
pub use fuel_tx::{UpgradePurpose, UploadSubsection};
use fuel_types::{Bytes32, Salt, bytes::padded_len_usize};
use itertools::Itertools;
use script_tx_estimator::ScriptTxEstimator;
use std::iter::repeat_n;
use std::{
collections::HashMap,
fmt::{Debug, Formatter},
iter::repeat,
sync::Arc,
};
use crate::{
constants::{DEFAULT_GAS_ESTIMATION_BLOCK_HORIZON, SIGNATURE_WITNESS_SIZE, WORD_SIZE},
traits::Signer,
types::{
Address, AssetId, ContractId, DryRunner,
coin::Coin,
coin_type::CoinType,
errors::{Result, error, error_transaction},
input::Input,
message::Message,
transaction::{
CreateTransaction, EstimablePredicates, ScriptTransaction, Transaction, TxPolicies,
UpgradeTransaction, UploadTransaction,
},
},
utils::{calculate_witnesses_size, sealed},
};
mod blob;
mod script_tx_estimator;
pub use blob::*;
const GAS_ESTIMATION_BLOCK_HORIZON: u32 = DEFAULT_GAS_ESTIMATION_BLOCK_HORIZON;
#[derive(Debug, Clone, Default)]
struct UnresolvedWitnessIndexes {
owner_to_idx_offset: HashMap<Address, u64>,
}
#[cfg_attr(not(target_arch = "wasm32"), async_trait)]
pub trait BuildableTransaction: sealed::Sealed {
type TxType: Transaction;
type Strategy;
fn with_build_strategy(self, strategy: Self::Strategy) -> Self;
async fn build(self, provider: impl DryRunner) -> Result<Self::TxType>;
}
impl sealed::Sealed for ScriptTransactionBuilder {}
#[derive(Debug, Clone, Default)]
pub enum ScriptBuildStrategy {
/// Transaction is estimated and signatures are automatically added.
#[default]
Complete,
/// Transaction is estimated but no signatures are added.
/// Building without signatures will set the witness indexes of signed coins in the
/// order as they appear in the inputs. Multiple coins with the same owner will have
/// the same witness index. Make sure you sign the built transaction in the expected order.
NoSignatures,
/// No estimation is done and no signatures are added. Fake coins are added if no spendable inputs
/// are present. Meant only for transactions that are to be dry-run with validations off.
/// Useful for reading state with unfunded accounts.
StateReadOnly,
}
#[derive(Debug, Clone, Default)]
pub enum Strategy {
/// Transaction is estimated and signatures are automatically added.
#[default]
Complete,
/// Transaction is estimated but no signatures are added.
/// Building without signatures will set the witness indexes of signed coins in the
/// order as they appear in the inputs. Multiple coins with the same owner will have
/// the same witness index. Make sure you sign the built transaction in the expected order.
NoSignatures,
}
#[cfg_attr(not(target_arch = "wasm32"), async_trait)]
impl BuildableTransaction for ScriptTransactionBuilder {
type TxType = ScriptTransaction;
type Strategy = ScriptBuildStrategy;
fn with_build_strategy(mut self, strategy: Self::Strategy) -> Self {
self.build_strategy = strategy;
self
}
async fn build(self, provider: impl DryRunner) -> Result<Self::TxType> {
self.build(provider).await
}
}
impl sealed::Sealed for CreateTransactionBuilder {}
#[cfg_attr(not(target_arch = "wasm32"), async_trait)]
impl BuildableTransaction for CreateTransactionBuilder {
type TxType = CreateTransaction;
type Strategy = Strategy;
fn with_build_strategy(mut self, strategy: Self::Strategy) -> Self {
self.build_strategy = strategy;
self
}
async fn build(self, provider: impl DryRunner) -> Result<Self::TxType> {
self.build(provider).await
}
}
impl sealed::Sealed for UploadTransactionBuilder {}
#[cfg_attr(not(target_arch = "wasm32"), async_trait)]
impl BuildableTransaction for UploadTransactionBuilder {
type TxType = UploadTransaction;
type Strategy = Strategy;
fn with_build_strategy(mut self, strategy: Self::Strategy) -> Self {
self.build_strategy = strategy;
self
}
async fn build(self, provider: impl DryRunner) -> Result<Self::TxType> {
self.build(provider).await
}
}
impl sealed::Sealed for UpgradeTransactionBuilder {}
#[cfg_attr(not(target_arch = "wasm32"), async_trait)]
impl BuildableTransaction for UpgradeTransactionBuilder {
type TxType = UpgradeTransaction;
type Strategy = Strategy;
fn with_build_strategy(mut self, strategy: Self::Strategy) -> Self {
self.build_strategy = strategy;
self
}
async fn build(self, provider: impl DryRunner) -> Result<Self::TxType> {
self.build(provider).await
}
}
#[cfg_attr(not(target_arch = "wasm32"), async_trait)]
pub trait TransactionBuilder: BuildableTransaction + Send + sealed::Sealed {
type TxType: Transaction;
fn add_signer(&mut self, signer: impl Signer + Send + Sync + 'static) -> Result<&mut Self>;
fn add_signers<'a>(
&mut self,
signers: impl IntoIterator<Item = &'a std::sync::Arc<dyn Signer + Send + Sync>>,
) -> Result<&mut Self>;
async fn estimate_max_fee(&self, provider: impl DryRunner) -> Result<u64>;
fn enable_burn(self, enable: bool) -> Self;
fn with_tx_policies(self, tx_policies: TxPolicies) -> Self;
fn with_inputs(self, inputs: Vec<Input>) -> Self;
fn with_outputs(self, outputs: Vec<Output>) -> Self;
fn with_witnesses(self, witnesses: Vec<Witness>) -> Self;
fn inputs(&self) -> &Vec<Input>;
fn inputs_mut(&mut self) -> &mut Vec<Input>;
fn outputs(&self) -> &Vec<Output>;
fn outputs_mut(&mut self) -> &mut Vec<Output>;
fn witnesses(&self) -> &Vec<Witness>;
fn witnesses_mut(&mut self) -> &mut Vec<Witness>;
fn with_estimation_horizon(self, block_horizon: u32) -> Self;
}
macro_rules! impl_tx_builder_trait {
($ty: ty, $tx_ty: ident) => {
#[cfg_attr(not(target_arch = "wasm32"), async_trait)]
impl $crate::types::transaction_builders::TransactionBuilder for $ty {
type TxType = $tx_ty;
fn add_signer(&mut self, signer: impl Signer + Send + Sync + 'static) -> Result<&mut Self> {
self.validate_no_signer_available(&signer.address())?;
let index_offset = self.unresolved_signers.len() as u64;
self.unresolved_witness_indexes
.owner_to_idx_offset
.insert(signer.address().clone(), index_offset);
self.unresolved_signers.push(std::sync::Arc::new(signer));
Ok(self)
}
fn add_signers<'a>(&mut self, signers: impl IntoIterator<Item=&'a std::sync::Arc<dyn Signer + Send + Sync>>) -> Result<&mut Self> {
for signer in signers {
self.validate_no_signer_available(&signer.address())?;
let index_offset = self.unresolved_signers.len() as u64;
self.unresolved_witness_indexes
.owner_to_idx_offset
.insert(signer.address().clone(), index_offset);
self.unresolved_signers.push(signer.clone());
}
Ok(self)
}
async fn estimate_max_fee(&self, provider: impl DryRunner) -> Result<u64> {
let mut fee_estimation_tb = self
.clone()
.with_build_strategy(Self::Strategy::NoSignatures);
// Add a temporary witness for every `Signer` to include them in the fee
// estimation.
let witness: Witness = Signature::default().as_ref().into();
fee_estimation_tb
.witnesses_mut()
.extend(repeat(witness).take(self.unresolved_signers.len()));
// Temporarily enable burning to avoid errors when calculating the fee.
let fee_estimation_tb = fee_estimation_tb.enable_burn(true);
let mut tx = $crate::types::transaction_builders::BuildableTransaction::build(
fee_estimation_tb,
&provider,
)
.await?;
if tx.is_using_predicates() {
tx.estimate_predicates(&provider, None).await?;
}
let consensus_parameters = provider.consensus_parameters().await?;
let gas_price = provider
.estimate_gas_price(self.gas_price_estimation_block_horizon)
.await?;
$crate::types::transaction_builders::estimate_max_fee_w_tolerance(
tx.tx,
self.max_fee_estimation_tolerance,
gas_price,
&consensus_parameters,
)
}
fn enable_burn(mut self, enable: bool) -> Self {
self.enable_burn = enable;
self
}
fn with_tx_policies(mut self, tx_policies: TxPolicies) -> Self {
self.tx_policies = tx_policies;
self
}
fn with_inputs(mut self, inputs: Vec<Input>) -> Self {
self.inputs = inputs;
self
}
fn with_outputs(mut self, outputs: Vec<Output>) -> Self {
self.outputs = outputs;
self
}
fn with_witnesses(mut self, witnesses: Vec<Witness>) -> Self {
self.witnesses = witnesses;
self
}
fn inputs(&self) -> &Vec<Input> {
self.inputs.as_ref()
}
fn inputs_mut(&mut self) -> &mut Vec<Input> {
&mut self.inputs
}
fn outputs(&self) -> &Vec<Output> {
self.outputs.as_ref()
}
fn outputs_mut(&mut self) -> &mut Vec<Output> {
&mut self.outputs
}
fn witnesses(&self) -> &Vec<Witness> {
self.witnesses.as_ref()
}
fn witnesses_mut(&mut self) -> &mut Vec<Witness> {
&mut self.witnesses
}
fn with_estimation_horizon(mut self, block_horizon: u32) -> Self {
self.gas_price_estimation_block_horizon = block_horizon;
self
}
}
impl $ty {
fn validate_no_signer_available(&self, address: &$crate::types::Address) -> Result<()> {
if self
.unresolved_witness_indexes
.owner_to_idx_offset
.contains_key(address)
{
return Err(error_transaction!(
Builder,
"already added `Signer` with address: `{address}`"
));
}
Ok(())
}
fn set_witness_indexes(&mut self) {
use $crate::types::transaction_builders::TransactionBuilder;
self.unresolved_witness_indexes.owner_to_idx_offset = self
.inputs()
.iter()
.filter_map(|input| match input {
Input::ResourceSigned { resource } => resource.owner(),
_ => None,
})
.unique()
.cloned()
.enumerate()
.map(|(idx, owner)| (owner, idx as u64))
.collect();
}
fn generate_fuel_policies(&self) -> Result<Policies> {
let witness_limit = match self.tx_policies.witness_limit() {
Some(limit) => limit,
None => self.calculate_witnesses_size()?,
};
let mut policies = Policies::default().with_witness_limit(witness_limit);
// `MaxFee` set to `tip` or `0` for `dry_run`
policies.set(PolicyType::MaxFee, self.tx_policies.tip().or(Some(0)));
policies.set(PolicyType::Maturity, self.tx_policies.maturity());
policies.set(PolicyType::Tip, self.tx_policies.tip());
policies.set(PolicyType::Expiration, self.tx_policies.expiration());
policies.set(PolicyType::Owner, self.tx_policies.owner());
Ok(policies)
}
fn is_using_predicates(&self) -> bool {
use $crate::types::transaction_builders::TransactionBuilder;
self.inputs()
.iter()
.any(|input| matches!(input, Input::ResourcePredicate { .. }))
}
fn intercept_burn(&self, base_asset_id: &$crate::types::AssetId) -> Result<()> {
use std::collections::HashSet;
if self.enable_burn {
return Ok(());
}
let assets_w_change = self
.outputs
.iter()
.filter_map(|output| match output {
Output::Change { asset_id, .. } => Some(*asset_id),
_ => None,
})
.collect::<HashSet<_>>();
let input_assets = self
.inputs
.iter()
.filter_map(|input| match input {
Input::ResourceSigned { resource } |
Input::ResourcePredicate { resource, .. } => resource.asset_id(*base_asset_id),
_ => None,
})
.collect::<HashSet<_>>();
let diff = input_assets.difference(&assets_w_change).collect_vec();
if !diff.is_empty() {
return Err(error_transaction!(
Builder,
"the following assets have no change outputs and may be burned unintentionally: {:?}. \
To resolve this, either add the necessary change outputs manually or explicitly allow asset burning \
by calling `.enable_burn(true)` on the transaction builder.",
diff
));
}
Ok(())
}
fn num_witnesses(&self) -> Result<u16> {
use $crate::types::transaction_builders::TransactionBuilder;
let num_witnesses = self.witnesses().len();
if num_witnesses + self.unresolved_signers.len() > u16::MAX as usize {
return Err(error_transaction!(
Builder,
"tx exceeds maximum number of witnesses"
));
}
Ok(num_witnesses as u16)
}
fn calculate_witnesses_size(&self) -> Result<u64> {
let witnesses_size = calculate_witnesses_size(&self.witnesses);
let signature_size = SIGNATURE_WITNESS_SIZE
* self.unresolved_witness_indexes.owner_to_idx_offset.len();
let padded_len = padded_len_usize(witnesses_size + signature_size)
.ok_or_else(|| error!(Other, "witnesses size overflow"))?;
Ok(padded_len as u64)
}
async fn set_max_fee_policy<T: Clone + PoliciesField + Chargeable + Into<$tx_ty>>(
tx: &mut T,
provider: impl DryRunner,
block_horizon: u32,
is_using_predicates: bool,
max_fee_estimation_tolerance: f32,
) -> Result<()> {
let mut wrapper_tx: $tx_ty = tx.clone().into();
if is_using_predicates {
wrapper_tx.estimate_predicates(&provider, None).await?;
}
let gas_price = provider.estimate_gas_price(block_horizon).await?;
let consensus_parameters = provider.consensus_parameters().await?;
let max_fee = $crate::types::transaction_builders::estimate_max_fee_w_tolerance(
wrapper_tx.tx,
max_fee_estimation_tolerance,
gas_price,
&consensus_parameters,
)?;
tx.policies_mut().set(PolicyType::MaxFee, Some(max_fee));
Ok(())
}
}
};
}
pub(crate) use impl_tx_builder_trait;
pub(crate) fn estimate_max_fee_w_tolerance<T: Chargeable>(
tx: T,
tolerance: f32,
gas_price: u64,
consensus_parameters: &ConsensusParameters,
) -> Result<u64> {
let gas_costs = &consensus_parameters.gas_costs();
let fee_params = consensus_parameters.fee_params();
let tx_fee = TransactionFee::checked_from_tx(gas_costs, fee_params, &tx, gas_price).ok_or(
error_transaction!(
Builder,
"error calculating `TransactionFee` in `TransactionBuilder`"
),
)?;
let max_fee_w_tolerance = tx_fee.max_fee() as f64 * (1.0 + f64::from(tolerance));
Ok(max_fee_w_tolerance.ceil() as u64)
}
impl Debug for dyn Signer + Send + Sync {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Signer")
.field("address", &self.address())
.finish()
}
}
/// Controls the SDK behavior regarding variable transaction outputs.
///
/// # Warning
///
/// Estimation of variable outputs is performed by saturating the transaction with variable outputs
/// and counting the number of outputs used. This process can be particularly unreliable in cases
/// where the script introspects the number of variable outputs and adjusts its logic accordingly.
/// The script could theoretically mint outputs until all variable outputs are utilized.
///
/// In such scenarios, estimation of necessary variable outputs becomes nearly impossible.
///
/// It is advised to avoid relying on automatic estimation of variable outputs if the script
/// contains logic that dynamically adjusts based on the number of outputs.
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum VariableOutputPolicy {
/// Perform a dry run of the transaction estimating the minimum number of variable outputs to
/// add.
EstimateMinimum,
/// Add exactly these many variable outputs to the transaction.
Exactly(usize),
}
impl Default for VariableOutputPolicy {
fn default() -> Self {
Self::Exactly(0)
}
}
#[derive(Debug, Clone)]
pub struct ScriptTransactionBuilder {
pub script: Vec<u8>,
pub script_data: Vec<u8>,
pub inputs: Vec<Input>,
pub outputs: Vec<Output>,
pub witnesses: Vec<Witness>,
pub tx_policies: TxPolicies,
pub gas_estimation_tolerance: f32,
pub max_fee_estimation_tolerance: f32,
pub gas_price_estimation_block_horizon: u32,
pub variable_output_policy: VariableOutputPolicy,
pub build_strategy: ScriptBuildStrategy,
unresolved_witness_indexes: UnresolvedWitnessIndexes,
unresolved_signers: Vec<Arc<dyn Signer + Send + Sync>>,
enable_burn: bool,
}
impl Default for ScriptTransactionBuilder {
fn default() -> Self {
Self {
script: Default::default(),
script_data: Default::default(),
inputs: Default::default(),
outputs: Default::default(),
witnesses: Default::default(),
tx_policies: Default::default(),
gas_estimation_tolerance: Default::default(),
max_fee_estimation_tolerance: Default::default(),
gas_price_estimation_block_horizon: GAS_ESTIMATION_BLOCK_HORIZON,
variable_output_policy: Default::default(),
build_strategy: Default::default(),
unresolved_witness_indexes: Default::default(),
unresolved_signers: Default::default(),
enable_burn: false,
}
}
}
#[derive(Debug, Clone)]
pub struct CreateTransactionBuilder {
pub bytecode_length: u64,
pub bytecode_witness_index: u16,
pub storage_slots: Vec<StorageSlot>,
pub inputs: Vec<Input>,
pub outputs: Vec<Output>,
pub witnesses: Vec<Witness>,
pub tx_policies: TxPolicies,
pub salt: Salt,
pub gas_price_estimation_block_horizon: u32,
pub max_fee_estimation_tolerance: f32,
pub build_strategy: Strategy,
unresolved_witness_indexes: UnresolvedWitnessIndexes,
unresolved_signers: Vec<Arc<dyn Signer + Send + Sync>>,
enable_burn: bool,
}
impl Default for CreateTransactionBuilder {
fn default() -> Self {
Self {
bytecode_length: Default::default(),
bytecode_witness_index: Default::default(),
storage_slots: Default::default(),
inputs: Default::default(),
outputs: Default::default(),
witnesses: Default::default(),
tx_policies: Default::default(),
salt: Default::default(),
gas_price_estimation_block_horizon: GAS_ESTIMATION_BLOCK_HORIZON,
max_fee_estimation_tolerance: Default::default(),
build_strategy: Default::default(),
unresolved_witness_indexes: Default::default(),
unresolved_signers: Default::default(),
enable_burn: false,
}
}
}
#[derive(Debug, Clone)]
pub struct UploadTransactionBuilder {
/// The root of the Merkle tree is created over the bytecode.
pub root: Bytes32,
/// The witness index of the subsection of the bytecode.
pub witness_index: u16,
/// The index of the subsection of the bytecode.
pub subsection_index: u16,
/// The total number of subsections on which bytecode was divided.
pub subsections_number: u16,
/// The proof set helps to verify the connection of the subsection to the `root`.
pub proof_set: Vec<Bytes32>,
pub inputs: Vec<Input>,
pub outputs: Vec<Output>,
pub witnesses: Vec<Witness>,
pub tx_policies: TxPolicies,
pub gas_price_estimation_block_horizon: u32,
pub max_fee_estimation_tolerance: f32,
pub build_strategy: Strategy,
unresolved_witness_indexes: UnresolvedWitnessIndexes,
unresolved_signers: Vec<Arc<dyn Signer + Send + Sync>>,
enable_burn: bool,
}
impl Default for UploadTransactionBuilder {
fn default() -> Self {
Self {
root: Default::default(),
witness_index: Default::default(),
subsection_index: Default::default(),
subsections_number: Default::default(),
proof_set: Default::default(),
inputs: Default::default(),
outputs: Default::default(),
witnesses: Default::default(),
tx_policies: Default::default(),
gas_price_estimation_block_horizon: GAS_ESTIMATION_BLOCK_HORIZON,
max_fee_estimation_tolerance: Default::default(),
build_strategy: Default::default(),
unresolved_witness_indexes: Default::default(),
unresolved_signers: Default::default(),
enable_burn: false,
}
}
}
#[derive(Debug, Clone)]
pub struct UpgradeTransactionBuilder {
/// The purpose of the upgrade.
pub purpose: UpgradePurpose,
pub inputs: Vec<Input>,
pub outputs: Vec<Output>,
pub witnesses: Vec<Witness>,
pub tx_policies: TxPolicies,
pub gas_price_estimation_block_horizon: u32,
pub max_fee_estimation_tolerance: f32,
pub build_strategy: Strategy,
unresolved_witness_indexes: UnresolvedWitnessIndexes,
unresolved_signers: Vec<Arc<dyn Signer + Send + Sync>>,
enable_burn: bool,
}
impl Default for UpgradeTransactionBuilder {
fn default() -> Self {
Self {
purpose: UpgradePurpose::StateTransition {
root: Default::default(),
},
inputs: Default::default(),
outputs: Default::default(),
witnesses: Default::default(),
tx_policies: Default::default(),
gas_price_estimation_block_horizon: GAS_ESTIMATION_BLOCK_HORIZON,
unresolved_witness_indexes: Default::default(),
unresolved_signers: Default::default(),
max_fee_estimation_tolerance: Default::default(),
build_strategy: Default::default(),
enable_burn: false,
}
}
}
impl_tx_builder_trait!(ScriptTransactionBuilder, ScriptTransaction);
impl_tx_builder_trait!(CreateTransactionBuilder, CreateTransaction);
impl_tx_builder_trait!(UploadTransactionBuilder, UploadTransaction);
impl_tx_builder_trait!(UpgradeTransactionBuilder, UpgradeTransaction);
impl ScriptTransactionBuilder {
async fn build(mut self, provider: impl DryRunner) -> Result<ScriptTransaction> {
let consensus_parameters = provider.consensus_parameters().await?;
self.intercept_burn(consensus_parameters.base_asset_id())?;
let is_using_predicates = self.is_using_predicates();
let tx = match self.build_strategy {
ScriptBuildStrategy::Complete => self.resolve_fuel_tx(&provider).await?,
ScriptBuildStrategy::NoSignatures => {
self.set_witness_indexes();
self.unresolved_signers = Default::default();
self.resolve_fuel_tx(&provider).await?
}
ScriptBuildStrategy::StateReadOnly => {
self.resolve_fuel_tx_for_state_reading(provider).await?
}
};
Ok(ScriptTransaction {
is_using_predicates,
tx,
})
}
async fn resolve_fuel_tx(self, dry_runner: impl DryRunner) -> Result<Script> {
let predefined_witnesses = self.witnesses.clone();
let mut script_tx_estimator = self.script_tx_estimator(predefined_witnesses, &dry_runner);
let mut tx = FuelTransaction::script(
0, // default value - will be overwritten
self.script.clone(),
self.script_data.clone(),
self.generate_fuel_policies()?,
resolve_fuel_inputs(
self.inputs.clone(),
self.num_witnesses()?,
&self.unresolved_witness_indexes,
)?,
self.outputs.clone(),
vec![],
);
self.add_variable_outputs(&mut script_tx_estimator, &mut tx)
.await?;
// should come after variable outputs because it can then reuse the dry run made for variable outputs
self.set_script_gas_limit(&mut script_tx_estimator, &mut tx)
.await?;
if let Some(max_fee) = self.tx_policies.max_fee() {
tx.policies_mut().set(PolicyType::MaxFee, Some(max_fee));
} else {
Self::set_max_fee_policy(
&mut tx,
&dry_runner,
self.gas_price_estimation_block_horizon,
self.is_using_predicates(),
self.max_fee_estimation_tolerance,
)
.await?;
}
self.set_witnesses(&mut tx, dry_runner).await?;
Ok(tx)
}
async fn resolve_fuel_tx_for_state_reading(self, dry_runner: impl DryRunner) -> Result<Script> {
let predefined_witnesses = self.witnesses.clone();
let mut script_tx_estimator = self.script_tx_estimator(predefined_witnesses, &dry_runner);
let mut tx = FuelTransaction::script(
0, // default value - will be overwritten
self.script.clone(),
self.script_data.clone(),
self.generate_fuel_policies()?,
resolve_fuel_inputs(
self.inputs.clone(),
self.num_witnesses()?,
&self.unresolved_witness_indexes,
)?,
self.outputs.clone(),
vec![],
);
let should_saturate_variable_outputs =
if let VariableOutputPolicy::Exactly(n) = self.variable_output_policy {
add_variable_outputs(&mut tx, n);
false
} else {
true
};
if let Some(max_fee) = self.tx_policies.max_fee() {
tx.policies_mut().set(PolicyType::MaxFee, Some(max_fee));
} else {
Self::set_max_fee_policy(
&mut tx,
&dry_runner,
self.gas_price_estimation_block_horizon,
self.is_using_predicates(),
self.max_fee_estimation_tolerance,
)
.await?;
}
script_tx_estimator
.prepare_for_estimation(&mut tx, should_saturate_variable_outputs)
.await?;
Ok(tx)
}
async fn set_witnesses(self, tx: &mut fuel_tx::Script, provider: impl DryRunner) -> Result<()> {
let missing_witnesses = generate_missing_witnesses(
tx.id(&provider.consensus_parameters().await?.chain_id()),
&self.unresolved_signers,
)
.await?;
*tx.witnesses_mut() = [self.witnesses, missing_witnesses].concat();
Ok(())
}
async fn set_script_gas_limit(
&self,
dry_runner: &mut ScriptTxEstimator<&impl DryRunner>,
tx: &mut fuel_tx::Script,
) -> Result<()> {
let has_no_code = self.script.is_empty();
let script_gas_limit = if let Some(gas_limit) = self.tx_policies.script_gas_limit() {
// Use the user defined value even if it makes the transaction revert.
gas_limit
} else if has_no_code {
0
} else {
let dry_run = if let Some(dry_run) = dry_runner.last_dry_run() {
// Even if the last dry run included variable outputs they only affect the transaction fee,
// the script's gas usage remains unchanged. By opting into variable output estimation, the user
// acknowledges the issues with tx introspection and asserts that there is no introspective logic
// based on the number of variable outputs.
//
// Therefore, we can trust the gas usage from the last dry run and reuse it, avoiding the need
// for an additional dry run.
dry_run
} else {
dry_runner.run(tx.clone(), false).await?
};
dry_run.gas_with_tolerance(self.gas_estimation_tolerance)
};
*tx.script_gas_limit_mut() = script_gas_limit;
Ok(())
}
fn script_tx_estimator<D>(
&self,
predefined_witnesses: Vec<Witness>,
dry_runner: D,
) -> ScriptTxEstimator<D>
where
D: DryRunner,
{
let num_unresolved_witnesses = self.unresolved_witness_indexes.owner_to_idx_offset.len();
ScriptTxEstimator::new(dry_runner, predefined_witnesses, num_unresolved_witnesses)
}
async fn add_variable_outputs(
&self,
dry_runner: &mut ScriptTxEstimator<&impl DryRunner>,
tx: &mut fuel_tx::Script,
) -> Result<()> {
let variable_outputs = match self.variable_output_policy {
VariableOutputPolicy::Exactly(num) => num,
VariableOutputPolicy::EstimateMinimum => {
dry_runner.run(tx.clone(), true).await?.variable_outputs
}
};
add_variable_outputs(tx, variable_outputs);
Ok(())
}
pub fn with_variable_output_policy(mut self, variable_outputs: VariableOutputPolicy) -> Self {
self.variable_output_policy = variable_outputs;
self
}
pub fn with_script(mut self, script: Vec<u8>) -> Self {
self.script = script;
self
}
pub fn with_script_data(mut self, script_data: Vec<u8>) -> Self {
self.script_data = script_data;
self
}
pub fn with_gas_estimation_tolerance(mut self, tolerance: f32) -> Self {
self.gas_estimation_tolerance = tolerance;
self
}
pub fn with_max_fee_estimation_tolerance(mut self, max_fee_estimation_tolerance: f32) -> Self {
self.max_fee_estimation_tolerance = max_fee_estimation_tolerance;
self
}
pub fn prepare_transfer(
inputs: Vec<Input>,
outputs: Vec<Output>,
tx_policies: TxPolicies,
) -> Self {
| rust | Apache-2.0 | 865e00c295de8b4a0a1ef7ac926c3c8266d5151b | 2026-01-04T15:31:59.450823Z | true |
FuelLabs/fuels-rs | https://github.com/FuelLabs/fuels-rs/blob/865e00c295de8b4a0a1ef7ac926c3c8266d5151b/packages/fuels-core/src/types/token.rs | packages/fuels-core/src/types/token.rs | use std::fmt;
use crate::types::{
core::U256,
errors::{Error, Result, error},
param_types::EnumVariants,
};
pub type EnumSelector = (u64, Token, EnumVariants);
#[derive(Debug, Clone, PartialEq, Eq, Default, serde::Serialize, serde::Deserialize)]
pub struct StaticStringToken {
pub(crate) data: String,
expected_len: Option<usize>,
}
impl StaticStringToken {
pub fn new(data: String, expected_len: Option<usize>) -> Self {
StaticStringToken { data, expected_len }
}
fn validate(&self) -> Result<()> {
if !self.data.is_ascii() {
return Err(error!(Codec, "string data can only have ascii values"));
}
if let Some(expected_len) = self.expected_len
&& self.data.len() != expected_len
{
return Err(error!(
Codec,
"string data has len {}, but the expected len is {}",
self.data.len(),
expected_len
));
}
Ok(())
}
pub fn get_encodable_str(&self) -> Result<&str> {
self.validate()?;
Ok(self.data.as_str())
}
}
impl TryFrom<StaticStringToken> for String {
type Error = Error;
fn try_from(string_token: StaticStringToken) -> Result<String> {
string_token.validate()?;
Ok(string_token.data)
}
}
#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
pub enum Token {
// Used for unit type variants in Enum. An "empty" enum is not represented as Enum<empty box>,
// because this way we can have both unit and non-unit type variants.
Unit,
Bool(bool),
U8(u8),
U16(u16),
U32(u32),
U64(u64),
U128(u128),
U256(U256),
B256([u8; 32]),
Bytes(Vec<u8>),
String(String),
RawSlice(Vec<u8>),
StringArray(StaticStringToken),
StringSlice(StaticStringToken),
Tuple(Vec<Token>),
Array(Vec<Token>),
Vector(Vec<Token>),
Struct(Vec<Token>),
Enum(Box<EnumSelector>),
}
impl fmt::Display for Token {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{self:?}")
}
}
impl Default for Token {
fn default() -> Self {
Token::U8(0)
}
}
| rust | Apache-2.0 | 865e00c295de8b4a0a1ef7ac926c3c8266d5151b | 2026-01-04T15:31:59.450823Z | false |
FuelLabs/fuels-rs | https://github.com/FuelLabs/fuels-rs/blob/865e00c295de8b4a0a1ef7ac926c3c8266d5151b/packages/fuels-core/src/types/param_types/from_type_application.rs | packages/fuels-core/src/types/param_types/from_type_application.rs | use std::{collections::HashMap, iter::zip};
use fuel_abi_types::{
abi::unified_program::{UnifiedTypeApplication, UnifiedTypeDeclaration},
utils::{extract_array_len, extract_generic_name, extract_str_len, has_tuple_format},
};
use crate::types::{
errors::{Error, Result, error},
param_types::{EnumVariants, NamedParamType, ParamType},
};
impl ParamType {
/// For when you need to convert a ABI JSON's UnifiedTypeApplication into a ParamType.
///
/// # Arguments
///
/// * `type_application`: The UnifiedTypeApplication you wish to convert into a ParamType
/// * `type_lookup`: A HashMap of UnifiedTypeDeclarations mentioned in the
/// UnifiedTypeApplication where the type id is the key.
pub fn try_from_type_application(
type_application: &UnifiedTypeApplication,
type_lookup: &HashMap<usize, UnifiedTypeDeclaration>,
) -> Result<Self> {
Type::try_from(type_application, type_lookup)?.try_into()
}
}
#[derive(Debug, Clone)]
struct Type {
name: String,
type_field: String,
generic_params: Vec<Type>,
components: Vec<Type>,
}
impl Type {
/// Will recursively drill down the given generic parameters until all types are
/// resolved.
///
/// # Arguments
///
/// * `type_application`: the type we wish to resolve
/// * `types`: all types used in the function call
pub fn try_from(
type_application: &UnifiedTypeApplication,
type_lookup: &HashMap<usize, UnifiedTypeDeclaration>,
) -> Result<Self> {
Self::resolve(type_application, type_lookup, &[])
}
fn resolve(
type_application: &UnifiedTypeApplication,
type_lookup: &HashMap<usize, UnifiedTypeDeclaration>,
parent_generic_params: &[(usize, Type)],
) -> Result<Self> {
let type_declaration = type_lookup.get(&type_application.type_id).ok_or_else(|| {
error!(
Codec,
"type id {} not found in type lookup", type_application.type_id
)
})?;
if extract_generic_name(&type_declaration.type_field).is_some() {
let (_, generic_type) = parent_generic_params
.iter()
.find(|(id, _)| *id == type_application.type_id)
.ok_or_else(|| {
error!(
Codec,
"type id {} not found in parent's generic parameters",
type_application.type_id
)
})?;
// The generic will inherit the name from the parent `type_application`
return Ok(Self {
name: type_application.name.clone(),
..generic_type.clone()
});
}
// Figure out what does the current type do with the inherited generic
// parameters and reestablish the mapping since the current type might have
// renamed the inherited generic parameters.
let generic_params_lookup = Self::determine_generics_for_type(
type_application,
type_lookup,
type_declaration,
parent_generic_params,
)?;
// Resolve the enclosed components (if any) with the newly resolved generic
// parameters.
let components = type_declaration
.components
.iter()
.flatten()
.map(|component| Self::resolve(component, type_lookup, &generic_params_lookup))
.collect::<Result<Vec<_>>>()?;
Ok(Type {
name: type_application.name.clone(),
type_field: type_declaration.type_field.clone(),
components,
generic_params: generic_params_lookup
.into_iter()
.map(|(_, ty)| ty)
.collect(),
})
}
/// For the given type generates generic_type_id -> Type mapping describing to
/// which types generic parameters should be resolved.
///
/// # Arguments
///
/// * `type_application`: The type on which the generic parameters are defined.
/// * `types`: All types used.
/// * `parent_generic_params`: The generic parameters as inherited from the
/// enclosing type (a struct/enum/array etc.).
fn determine_generics_for_type(
type_application: &UnifiedTypeApplication,
type_lookup: &HashMap<usize, UnifiedTypeDeclaration>,
type_declaration: &UnifiedTypeDeclaration,
parent_generic_params: &[(usize, Type)],
) -> Result<Vec<(usize, Self)>> {
match &type_declaration.type_parameters {
// The presence of type_parameters indicates that the current type
// (a struct or an enum) defines some generic parameters (i.e. SomeStruct<T, K>).
Some(params) if !params.is_empty() => {
// Determine what Types the generics will resolve to.
let generic_params_from_current_type = type_application
.type_arguments
.iter()
.flatten()
.map(|ty| Self::resolve(ty, type_lookup, parent_generic_params))
.collect::<Result<Vec<_>>>()?;
let generics_to_use = if !generic_params_from_current_type.is_empty() {
generic_params_from_current_type
} else {
// Types such as arrays and enums inherit and forward their
// generic parameters, without declaring their own.
parent_generic_params
.iter()
.map(|(_, ty)| ty)
.cloned()
.collect()
};
// All inherited but unused generic types are dropped. The rest are
// re-mapped to new type_ids since child types are free to rename
// the generic parameters as they see fit -- i.e.
// struct ParentStruct<T>{
// b: ChildStruct<T>
// }
// struct ChildStruct<K> {
// c: K
// }
Ok(zip(params.clone(), generics_to_use).collect())
}
_ => Ok(parent_generic_params.to_vec()),
}
}
}
impl TryFrom<Type> for ParamType {
type Error = Error;
fn try_from(value: Type) -> Result<Self> {
(&value).try_into()
}
}
impl TryFrom<&Type> for ParamType {
type Error = Error;
fn try_from(the_type: &Type) -> Result<Self> {
let matched_param_type = [
try_primitive,
try_array,
try_str_array,
try_str_slice,
try_tuple,
try_vector,
try_bytes,
try_std_string,
try_raw_slice,
try_enum,
try_u128,
try_struct,
]
.into_iter()
.map(|fun| fun(the_type))
.flat_map(|result| result.ok().flatten())
.next();
matched_param_type.map(Ok).unwrap_or_else(|| {
Err(error!(
Codec,
"type {} couldn't be converted into a ParamType", the_type.type_field
))
})
}
}
fn convert_into_param_types(coll: &[Type]) -> Result<Vec<ParamType>> {
coll.iter().map(ParamType::try_from).collect()
}
fn named_param_types(coll: &[Type]) -> Result<Vec<NamedParamType>> {
coll.iter()
.map(|ttype| Ok((ttype.name.clone(), ttype.try_into()?)))
.collect()
}
fn try_struct(the_type: &Type) -> Result<Option<ParamType>> {
let field = &the_type.type_field;
if field.starts_with("struct ") {
let fields = named_param_types(&the_type.components)?;
let generics = param_types(&the_type.generic_params)?;
return Ok(Some(ParamType::Struct {
name: the_type
.type_field
.strip_prefix("struct ")
.expect("has `struct`")
.to_string(),
fields,
generics,
}));
}
Ok(None)
}
fn try_vector(the_type: &Type) -> Result<Option<ParamType>> {
if !["struct std::vec::Vec", "struct Vec"].contains(&the_type.type_field.as_str()) {
return Ok(None);
}
if the_type.generic_params.len() != 1 {
return Err(error!(
Codec,
"`Vec` must have exactly one generic argument for its type. Found: `{:?}`",
the_type.generic_params
));
}
let vec_elem_type = convert_into_param_types(&the_type.generic_params)?.remove(0);
Ok(Some(ParamType::Vector(Box::new(vec_elem_type))))
}
fn try_u128(the_type: &Type) -> Result<Option<ParamType>> {
Ok(["struct std::u128::U128", "struct U128"]
.contains(&the_type.type_field.as_str())
.then_some(ParamType::U128))
}
fn try_bytes(the_type: &Type) -> Result<Option<ParamType>> {
Ok(["struct std::bytes::Bytes", "struct Bytes"]
.contains(&the_type.type_field.as_str())
.then_some(ParamType::Bytes))
}
fn try_std_string(the_type: &Type) -> Result<Option<ParamType>> {
Ok(["struct std::string::String", "struct String"]
.contains(&the_type.type_field.as_str())
.then_some(ParamType::String))
}
fn try_raw_slice(the_type: &Type) -> Result<Option<ParamType>> {
Ok((the_type.type_field == "raw untyped slice").then_some(ParamType::RawSlice))
}
fn try_enum(the_type: &Type) -> Result<Option<ParamType>> {
let field = &the_type.type_field;
if field.starts_with("enum ") {
let components = named_param_types(&the_type.components)?;
let enum_variants = EnumVariants::new(components)?;
let generics = param_types(&the_type.generic_params)?;
return Ok(Some(ParamType::Enum {
name: field.strip_prefix("enum ").expect("has `enum`").to_string(),
enum_variants,
generics,
}));
}
Ok(None)
}
fn try_tuple(the_type: &Type) -> Result<Option<ParamType>> {
let result = if has_tuple_format(&the_type.type_field) {
let tuple_elements = param_types(&the_type.components)?;
Some(ParamType::Tuple(tuple_elements))
} else {
None
};
Ok(result)
}
fn param_types(coll: &[Type]) -> Result<Vec<ParamType>> {
coll.iter().map(|t| t.try_into()).collect()
}
fn try_str_array(the_type: &Type) -> Result<Option<ParamType>> {
Ok(extract_str_len(&the_type.type_field).map(ParamType::StringArray))
}
fn try_str_slice(the_type: &Type) -> Result<Option<ParamType>> {
Ok(if the_type.type_field == "str" {
Some(ParamType::StringSlice)
} else {
None
})
}
fn try_array(the_type: &Type) -> Result<Option<ParamType>> {
if let Some(len) = extract_array_len(&the_type.type_field) {
return match the_type.components.as_slice() {
[single_type] => {
let array_type = single_type.try_into()?;
Ok(Some(ParamType::Array(Box::new(array_type), len)))
}
_ => Err(error!(
Codec,
"array must have elements of exactly one type. Array types: {:?}",
the_type.components
)),
};
}
Ok(None)
}
fn try_primitive(the_type: &Type) -> Result<Option<ParamType>> {
let result = match the_type.type_field.as_str() {
"bool" => Some(ParamType::Bool),
"u8" => Some(ParamType::U8),
"u16" => Some(ParamType::U16),
"u32" => Some(ParamType::U32),
"u64" => Some(ParamType::U64),
"u256" => Some(ParamType::U256),
"b256" => Some(ParamType::B256),
"()" => Some(ParamType::Unit),
"str" => Some(ParamType::StringSlice),
_ => None,
};
Ok(result)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn handles_simple_types() -> Result<()> {
let parse_param_type = |type_field: &str| {
let type_application = UnifiedTypeApplication {
name: "".to_string(),
type_id: 0,
type_arguments: None,
error_message: None,
};
let declarations = [UnifiedTypeDeclaration {
type_id: 0,
type_field: type_field.to_string(),
components: None,
type_parameters: None,
alias_of: None,
}];
let type_lookup = declarations
.into_iter()
.map(|decl| (decl.type_id, decl))
.collect::<HashMap<_, _>>();
ParamType::try_from_type_application(&type_application, &type_lookup)
};
assert_eq!(parse_param_type("()")?, ParamType::Unit);
assert_eq!(parse_param_type("bool")?, ParamType::Bool);
assert_eq!(parse_param_type("u8")?, ParamType::U8);
assert_eq!(parse_param_type("u16")?, ParamType::U16);
assert_eq!(parse_param_type("u32")?, ParamType::U32);
assert_eq!(parse_param_type("u64")?, ParamType::U64);
assert_eq!(parse_param_type("u256")?, ParamType::U256);
assert_eq!(parse_param_type("b256")?, ParamType::B256);
assert_eq!(parse_param_type("str[21]")?, ParamType::StringArray(21));
assert_eq!(parse_param_type("str")?, ParamType::StringSlice);
Ok(())
}
#[test]
fn handles_arrays() -> Result<()> {
// given
let type_application = UnifiedTypeApplication {
name: "".to_string(),
type_id: 0,
type_arguments: None,
error_message: None,
};
let declarations = [
UnifiedTypeDeclaration {
type_id: 0,
type_field: "[_; 10]".to_string(),
components: Some(vec![UnifiedTypeApplication {
name: "__array_element".to_string(),
type_id: 1,
type_arguments: None,
error_message: None,
}]),
type_parameters: None,
alias_of: None,
},
UnifiedTypeDeclaration {
type_id: 1,
type_field: "u8".to_string(),
components: None,
type_parameters: None,
alias_of: None,
},
];
let type_lookup = declarations
.into_iter()
.map(|decl| (decl.type_id, decl))
.collect::<HashMap<_, _>>();
// when
let result = ParamType::try_from_type_application(&type_application, &type_lookup)?;
// then
assert_eq!(result, ParamType::Array(Box::new(ParamType::U8), 10));
Ok(())
}
#[test]
fn handles_vectors() -> Result<()> {
// given
let declarations = [
UnifiedTypeDeclaration {
type_id: 1,
type_field: "generic T".to_string(),
components: None,
type_parameters: None,
alias_of: None,
},
UnifiedTypeDeclaration {
type_id: 2,
type_field: "raw untyped ptr".to_string(),
components: None,
type_parameters: None,
alias_of: None,
},
UnifiedTypeDeclaration {
type_id: 3,
type_field: "struct std::vec::RawVec".to_string(),
components: Some(vec![
UnifiedTypeApplication {
name: "ptr".to_string(),
type_id: 2,
type_arguments: None,
error_message: None,
},
UnifiedTypeApplication {
name: "cap".to_string(),
type_id: 5,
type_arguments: None,
error_message: None,
},
]),
type_parameters: Some(vec![1]),
alias_of: None,
},
UnifiedTypeDeclaration {
type_id: 4,
type_field: "struct std::vec::Vec".to_string(),
components: Some(vec![
UnifiedTypeApplication {
name: "buf".to_string(),
type_id: 3,
type_arguments: Some(vec![UnifiedTypeApplication {
name: "".to_string(),
type_id: 1,
type_arguments: None,
error_message: None,
}]),
error_message: None,
},
UnifiedTypeApplication {
name: "len".to_string(),
type_id: 5,
type_arguments: None,
error_message: None,
},
]),
type_parameters: Some(vec![1]),
alias_of: None,
},
UnifiedTypeDeclaration {
type_id: 5,
type_field: "u64".to_string(),
components: None,
type_parameters: None,
alias_of: None,
},
UnifiedTypeDeclaration {
type_id: 6,
type_field: "u8".to_string(),
components: None,
type_parameters: None,
alias_of: None,
},
];
let type_application = UnifiedTypeApplication {
name: "arg".to_string(),
type_id: 4,
type_arguments: Some(vec![UnifiedTypeApplication {
name: "".to_string(),
type_id: 6,
type_arguments: None,
error_message: None,
}]),
error_message: None,
};
let type_lookup = declarations
.into_iter()
.map(|decl| (decl.type_id, decl))
.collect::<HashMap<_, _>>();
// when
let result = ParamType::try_from_type_application(&type_application, &type_lookup)?;
// then
assert_eq!(result, ParamType::Vector(Box::new(ParamType::U8)));
Ok(())
}
#[test]
fn handles_structs() -> Result<()> {
// given
let declarations = [
UnifiedTypeDeclaration {
type_id: 1,
type_field: "generic T".to_string(),
components: None,
type_parameters: None,
alias_of: None,
},
UnifiedTypeDeclaration {
type_id: 2,
type_field: "struct SomeStruct".to_string(),
components: Some(vec![UnifiedTypeApplication {
name: "field".to_string(),
type_id: 1,
type_arguments: None,
error_message: None,
}]),
type_parameters: Some(vec![1]),
alias_of: None,
},
UnifiedTypeDeclaration {
type_id: 3,
type_field: "u8".to_string(),
components: None,
type_parameters: None,
alias_of: None,
},
];
let type_application = UnifiedTypeApplication {
name: "arg".to_string(),
type_id: 2,
type_arguments: Some(vec![UnifiedTypeApplication {
name: "".to_string(),
type_id: 3,
type_arguments: None,
error_message: None,
}]),
error_message: None,
};
let type_lookup = declarations
.into_iter()
.map(|decl| (decl.type_id, decl))
.collect::<HashMap<_, _>>();
// when
let result = ParamType::try_from_type_application(&type_application, &type_lookup)?;
// then
assert_eq!(
result,
ParamType::Struct {
name: "SomeStruct".to_string(),
fields: vec![("field".to_string(), ParamType::U8)],
generics: vec![ParamType::U8]
}
);
Ok(())
}
#[test]
fn handles_enums() -> Result<()> {
// given
let declarations = [
UnifiedTypeDeclaration {
type_id: 1,
type_field: "generic T".to_string(),
components: None,
type_parameters: None,
alias_of: None,
},
UnifiedTypeDeclaration {
type_id: 2,
type_field: "enum SomeEnum".to_string(),
components: Some(vec![UnifiedTypeApplication {
name: "Variant".to_string(),
type_id: 1,
type_arguments: None,
error_message: None,
}]),
type_parameters: Some(vec![1]),
alias_of: None,
},
UnifiedTypeDeclaration {
type_id: 3,
type_field: "u8".to_string(),
components: None,
type_parameters: None,
alias_of: None,
},
];
let type_application = UnifiedTypeApplication {
name: "arg".to_string(),
type_id: 2,
type_arguments: Some(vec![UnifiedTypeApplication {
name: "".to_string(),
type_id: 3,
type_arguments: None,
error_message: None,
}]),
error_message: None,
};
let type_lookup = declarations
.into_iter()
.map(|decl| (decl.type_id, decl))
.collect::<HashMap<_, _>>();
// when
let result = ParamType::try_from_type_application(&type_application, &type_lookup)?;
// then
assert_eq!(
result,
ParamType::Enum {
name: "SomeEnum".to_string(),
enum_variants: EnumVariants::new(vec![("Variant".to_string(), ParamType::U8)])?,
generics: vec![ParamType::U8]
}
);
Ok(())
}
#[test]
fn handles_tuples() -> Result<()> {
// given
let declarations = [
UnifiedTypeDeclaration {
type_id: 1,
type_field: "(_, _)".to_string(),
components: Some(vec![
UnifiedTypeApplication {
name: "__tuple_element".to_string(),
type_id: 3,
type_arguments: None,
error_message: None,
},
UnifiedTypeApplication {
name: "__tuple_element".to_string(),
type_id: 2,
type_arguments: None,
error_message: None,
},
]),
type_parameters: None,
alias_of: None,
},
UnifiedTypeDeclaration {
type_id: 2,
type_field: "str[15]".to_string(),
components: None,
type_parameters: None,
alias_of: None,
},
UnifiedTypeDeclaration {
type_id: 3,
type_field: "u8".to_string(),
components: None,
type_parameters: None,
alias_of: None,
},
];
let type_application = UnifiedTypeApplication {
name: "arg".to_string(),
type_id: 1,
type_arguments: None,
error_message: None,
};
let type_lookup = declarations
.into_iter()
.map(|decl| (decl.type_id, decl))
.collect::<HashMap<_, _>>();
// when
let result = ParamType::try_from_type_application(&type_application, &type_lookup)?;
// then
assert_eq!(
result,
ParamType::Tuple(vec![ParamType::U8, ParamType::StringArray(15)])
);
Ok(())
}
#[test]
fn ultimate_example() -> Result<()> {
// given
let declarations = [
UnifiedTypeDeclaration {
type_id: 1,
type_field: "(_, _)".to_string(),
components: Some(vec![
UnifiedTypeApplication {
name: "__tuple_element".to_string(),
type_id: 11,
type_arguments: None,
error_message: None,
},
UnifiedTypeApplication {
name: "__tuple_element".to_string(),
type_id: 11,
type_arguments: None,
error_message: None,
},
]),
type_parameters: None,
alias_of: None,
},
UnifiedTypeDeclaration {
type_id: 2,
type_field: "(_, _)".to_string(),
components: Some(vec![
UnifiedTypeApplication {
name: "__tuple_element".to_string(),
type_id: 4,
type_arguments: None,
error_message: None,
},
UnifiedTypeApplication {
name: "__tuple_element".to_string(),
type_id: 24,
type_arguments: None,
error_message: None,
},
]),
type_parameters: None,
alias_of: None,
},
UnifiedTypeDeclaration {
type_id: 3,
type_field: "(_, _)".to_string(),
components: Some(vec![
UnifiedTypeApplication {
name: "__tuple_element".to_string(),
type_id: 5,
type_arguments: None,
error_message: None,
},
UnifiedTypeApplication {
name: "__tuple_element".to_string(),
type_id: 13,
type_arguments: None,
error_message: None,
},
]),
type_parameters: None,
alias_of: None,
},
UnifiedTypeDeclaration {
type_id: 4,
type_field: "[_; 1]".to_string(),
components: Some(vec![UnifiedTypeApplication {
name: "__array_element".to_string(),
type_id: 8,
type_arguments: Some(vec![UnifiedTypeApplication {
name: "".to_string(),
type_id: 22,
type_arguments: Some(vec![UnifiedTypeApplication {
name: "".to_string(),
type_id: 21,
type_arguments: Some(vec![UnifiedTypeApplication {
name: "".to_string(),
type_id: 18,
type_arguments: Some(vec![UnifiedTypeApplication {
name: "".to_string(),
type_id: 13,
type_arguments: None,
error_message: None,
}]),
error_message: None,
}]),
error_message: None,
}]),
error_message: None,
}]),
error_message: None,
}]),
type_parameters: None,
alias_of: None,
},
UnifiedTypeDeclaration {
type_id: 5,
type_field: "[_; 2]".to_string(),
components: Some(vec![UnifiedTypeApplication {
name: "__array_element".to_string(),
type_id: 14,
type_arguments: None,
error_message: None,
}]),
type_parameters: None,
alias_of: None,
},
UnifiedTypeDeclaration {
type_id: 6,
type_field: "[_; 2]".to_string(),
components: Some(vec![UnifiedTypeApplication {
name: "__array_element".to_string(),
type_id: 10,
type_arguments: None,
error_message: None,
}]),
type_parameters: None,
alias_of: None,
},
UnifiedTypeDeclaration {
type_id: 7,
type_field: "b256".to_string(),
components: None,
type_parameters: None,
alias_of: None,
},
UnifiedTypeDeclaration {
type_id: 8,
type_field: "enum EnumWGeneric".to_string(),
components: Some(vec![
UnifiedTypeApplication {
name: "A".to_string(),
type_id: 25,
type_arguments: None,
error_message: None,
},
UnifiedTypeApplication {
name: "B".to_string(),
type_id: 12,
type_arguments: None,
error_message: None,
},
]),
type_parameters: Some(vec![12]),
alias_of: None,
},
UnifiedTypeDeclaration {
type_id: 9,
type_field: "generic K".to_string(),
components: None,
type_parameters: None,
alias_of: None,
},
UnifiedTypeDeclaration {
type_id: 10,
type_field: "generic L".to_string(),
components: None,
type_parameters: None,
alias_of: None,
},
UnifiedTypeDeclaration {
type_id: 11,
type_field: "generic M".to_string(),
components: None,
type_parameters: None,
alias_of: None,
},
UnifiedTypeDeclaration {
type_id: 12,
type_field: "generic N".to_string(),
components: None,
type_parameters: None,
alias_of: None,
},
UnifiedTypeDeclaration {
type_id: 13,
type_field: "generic T".to_string(),
components: None,
type_parameters: None,
alias_of: None,
},
UnifiedTypeDeclaration {
type_id: 14,
type_field: "generic U".to_string(),
components: None,
type_parameters: None,
alias_of: None,
},
UnifiedTypeDeclaration {
type_id: 15,
type_field: "raw untyped ptr".to_string(),
components: None,
type_parameters: None,
alias_of: None,
},
UnifiedTypeDeclaration {
type_id: 16,
type_field: "str[2]".to_string(),
components: None,
type_parameters: None,
alias_of: None,
},
UnifiedTypeDeclaration {
type_id: 17,
type_field: "struct MegaExample".to_string(),
components: Some(vec![
UnifiedTypeApplication {
name: "a".to_string(),
type_id: 3,
type_arguments: None,
error_message: None,
},
UnifiedTypeApplication {
name: "b".to_string(),
type_id: 23,
type_arguments: Some(vec![UnifiedTypeApplication {
name: "".to_string(),
type_id: 2,
| rust | Apache-2.0 | 865e00c295de8b4a0a1ef7ac926c3c8266d5151b | 2026-01-04T15:31:59.450823Z | true |
FuelLabs/fuels-rs | https://github.com/FuelLabs/fuels-rs/blob/865e00c295de8b4a0a1ef7ac926c3c8266d5151b/packages/fuels-core/src/types/param_types/param_type.rs | packages/fuels-core/src/types/param_types/param_type.rs | use crate::types::errors::{Result, error};
pub type NamedParamType = (String, ParamType);
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub enum ParamType {
Unit,
Bool,
U8,
U16,
U32,
U64,
U128,
U256,
B256,
Bytes,
String,
RawSlice,
StringArray(usize),
StringSlice,
Tuple(Vec<ParamType>),
Array(Box<ParamType>, usize),
Vector(Box<ParamType>),
Struct {
name: String,
fields: Vec<NamedParamType>,
generics: Vec<ParamType>,
},
Enum {
name: String,
enum_variants: EnumVariants,
generics: Vec<ParamType>,
},
}
pub enum ReturnLocation {
Return,
ReturnData,
}
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct EnumVariants {
variants: Vec<NamedParamType>,
}
impl EnumVariants {
pub fn new(variants: Vec<NamedParamType>) -> Result<EnumVariants> {
if variants.is_empty() {
return Err(error!(Other, "enum variants cannot be empty!"));
}
Ok(EnumVariants { variants })
}
pub fn variants(&self) -> &Vec<NamedParamType> {
&self.variants
}
pub fn param_types(&self) -> impl Iterator<Item = &ParamType> {
self.variants.iter().map(|(_, param_type)| param_type)
}
pub fn select_variant(&self, discriminant: u64) -> Result<&NamedParamType> {
self.variants.get(discriminant as usize).ok_or_else(|| {
error!(
Other,
"discriminant `{discriminant}` doesn't point to any variant: {:?}",
self.variants()
)
})
}
}
| rust | Apache-2.0 | 865e00c295de8b4a0a1ef7ac926c3c8266d5151b | 2026-01-04T15:31:59.450823Z | false |
FuelLabs/fuels-rs | https://github.com/FuelLabs/fuels-rs/blob/865e00c295de8b4a0a1ef7ac926c3c8266d5151b/packages/fuels-core/src/types/transaction_builders/blob.rs | packages/fuels-core/src/types/transaction_builders/blob.rs | use std::{fmt::Debug, iter::repeat, sync::Arc};
use async_trait::async_trait;
use fuel_crypto::Signature;
use fuel_tx::{
BlobIdExt, Chargeable, Output, Transaction as FuelTransaction, UniqueIdentifier, Witness,
field::{Policies as PoliciesField, Witnesses},
policies::{Policies, PolicyType},
};
use fuel_types::bytes::padded_len_usize;
use itertools::Itertools;
use super::{
BuildableTransaction, GAS_ESTIMATION_BLOCK_HORIZON, Strategy, TransactionBuilder,
UnresolvedWitnessIndexes, generate_missing_witnesses, impl_tx_builder_trait,
resolve_fuel_inputs,
};
use crate::{
constants::SIGNATURE_WITNESS_SIZE,
traits::Signer,
types::{
DryRunner,
errors::{Result, error, error_transaction},
input::Input,
transaction::{BlobTransaction, EstimablePredicates, Transaction, TxPolicies},
},
utils::{calculate_witnesses_size, sealed},
};
#[derive(Default, Clone, Debug, PartialEq)]
pub struct Blob {
data: Vec<u8>,
}
pub type BlobId = [u8; 32];
impl From<Vec<u8>> for Blob {
fn from(data: Vec<u8>) -> Self {
Self { data }
}
}
impl AsRef<[u8]> for Blob {
fn as_ref(&self) -> &[u8] {
&self.data
}
}
impl Blob {
pub fn new(data: Vec<u8>) -> Self {
Self { data }
}
pub fn len(&self) -> usize {
self.data.len()
}
pub fn is_empty(&self) -> bool {
self.data.is_empty()
}
pub fn id(&self) -> BlobId {
fuel_tx::BlobId::compute(&self.data).into()
}
pub fn bytes(&self) -> &[u8] {
self.data.as_slice()
}
fn as_blob_body(&self, witness_index: u16) -> fuel_tx::BlobBody {
fuel_tx::BlobBody {
id: self.id().into(),
witness_index,
}
}
}
impl From<Blob> for Vec<u8> {
fn from(value: Blob) -> Self {
value.data
}
}
impl From<Blob> for fuel_tx::Witness {
fn from(blob: Blob) -> Self {
blob.data.into()
}
}
#[derive(Debug, Clone)]
pub struct BlobTransactionBuilder {
pub inputs: Vec<Input>,
pub outputs: Vec<Output>,
pub witnesses: Vec<Witness>,
pub tx_policies: TxPolicies,
pub gas_price_estimation_block_horizon: u32,
pub max_fee_estimation_tolerance: f32,
pub build_strategy: Strategy,
pub blob: Blob,
unresolved_witness_indexes: UnresolvedWitnessIndexes,
unresolved_signers: Vec<Arc<dyn Signer + Send + Sync>>,
enable_burn: bool,
}
impl Default for BlobTransactionBuilder {
fn default() -> Self {
Self {
inputs: Default::default(),
outputs: Default::default(),
witnesses: Default::default(),
tx_policies: Default::default(),
gas_price_estimation_block_horizon: GAS_ESTIMATION_BLOCK_HORIZON,
max_fee_estimation_tolerance: Default::default(),
build_strategy: Default::default(),
blob: Default::default(),
unresolved_witness_indexes: Default::default(),
unresolved_signers: Default::default(),
enable_burn: false,
}
}
}
impl_tx_builder_trait!(BlobTransactionBuilder, BlobTransaction);
impl BlobTransactionBuilder {
/// Calculates the maximum possible blob size by determining the remaining space available in the current transaction before it reaches the maximum allowed size.
/// Note: This calculation only considers the transaction size limit and does not account for the maximum gas per transaction.
pub async fn estimate_max_blob_size(&self, provider: &impl DryRunner) -> Result<usize> {
let mut tb = self.clone();
tb.blob = Blob::new(vec![]);
let tx = tb
.with_build_strategy(Strategy::NoSignatures)
.build(provider)
.await?;
let current_tx_size = tx.size();
let max_tx_size = usize::try_from(
provider
.consensus_parameters()
.await?
.tx_params()
.max_size(),
)
.unwrap_or(usize::MAX);
Ok(max_tx_size.saturating_sub(current_tx_size))
}
pub async fn build(mut self, provider: impl DryRunner) -> Result<BlobTransaction> {
let consensus_parameters = provider.consensus_parameters().await?;
self.intercept_burn(consensus_parameters.base_asset_id())?;
let is_using_predicates = self.is_using_predicates();
let tx = match self.build_strategy {
Strategy::Complete => self.resolve_fuel_tx(&provider).await?,
Strategy::NoSignatures => {
self.set_witness_indexes();
self.unresolved_signers = Default::default();
self.resolve_fuel_tx(&provider).await?
}
};
Ok(BlobTransaction {
is_using_predicates,
tx,
})
}
async fn resolve_fuel_tx(mut self, provider: &impl DryRunner) -> Result<fuel_tx::Blob> {
let chain_id = provider.consensus_parameters().await?.chain_id();
let free_witness_index = self.num_witnesses()?;
let body = self.blob.as_blob_body(free_witness_index);
let blob_witness = std::mem::take(&mut self.blob).into();
self.witnesses_mut().push(blob_witness);
let num_witnesses = self.num_witnesses()?;
let policies = self.generate_fuel_policies()?;
let is_using_predicates = self.is_using_predicates();
let mut tx = FuelTransaction::blob(
body,
policies,
resolve_fuel_inputs(self.inputs, num_witnesses, &self.unresolved_witness_indexes)?,
self.outputs,
self.witnesses,
);
if let Some(max_fee) = self.tx_policies.max_fee() {
tx.policies_mut().set(PolicyType::MaxFee, Some(max_fee));
} else {
Self::set_max_fee_policy(
&mut tx,
&provider,
self.gas_price_estimation_block_horizon,
is_using_predicates,
self.max_fee_estimation_tolerance,
)
.await?;
}
let signatures =
generate_missing_witnesses(tx.id(&chain_id), &self.unresolved_signers).await?;
tx.witnesses_mut().extend(signatures);
Ok(tx)
}
pub fn with_blob(mut self, blob: Blob) -> Self {
self.blob = blob;
self
}
pub fn with_max_fee_estimation_tolerance(mut self, max_fee_estimation_tolerance: f32) -> Self {
self.max_fee_estimation_tolerance = max_fee_estimation_tolerance;
self
}
}
impl sealed::Sealed for BlobTransactionBuilder {}
#[cfg_attr(not(target_arch = "wasm32"), async_trait)]
impl BuildableTransaction for BlobTransactionBuilder {
type TxType = BlobTransaction;
type Strategy = Strategy;
fn with_build_strategy(mut self, strategy: Self::Strategy) -> Self {
self.build_strategy = strategy;
self
}
async fn build(self, provider: impl DryRunner) -> Result<Self::TxType> {
BlobTransactionBuilder::build(self, provider).await
}
}
| rust | Apache-2.0 | 865e00c295de8b4a0a1ef7ac926c3c8266d5151b | 2026-01-04T15:31:59.450823Z | false |
FuelLabs/fuels-rs | https://github.com/FuelLabs/fuels-rs/blob/865e00c295de8b4a0a1ef7ac926c3c8266d5151b/packages/fuels-core/src/types/transaction_builders/script_tx_estimator.rs | packages/fuels-core/src/types/transaction_builders/script_tx_estimator.rs | use std::iter::repeat_n;
use fuel_crypto::Signature;
use fuel_tx::{
AssetId, Chargeable, ConsensusParameters, Input as FuelInput, TxPointer, Witness,
field::{Inputs, Outputs, ScriptGasLimit, WitnessLimit, Witnesses},
input::coin::{CoinPredicate, CoinSigned},
};
use itertools::Itertools;
use crate::{
constants::WITNESS_STATIC_SIZE,
types::{DryRun, DryRunner, errors::Result},
};
pub(crate) struct ScriptTxEstimator<R> {
dry_runner: R,
predefined_witnesses: Vec<Witness>,
num_unresolved_witnesses: usize,
last_dry_run: Option<DryRun>,
}
impl<R> ScriptTxEstimator<R> {
pub fn new(
dry_runner: R,
predefined_witnesses: Vec<Witness>,
num_unresolved_witnesses: usize,
) -> Self {
Self {
dry_runner,
predefined_witnesses,
num_unresolved_witnesses,
last_dry_run: None,
}
}
}
impl<R: DryRunner> ScriptTxEstimator<R> {
pub async fn run(
&mut self,
mut tx: fuel_tx::Script,
saturate_variable_outputs: bool,
) -> Result<DryRun> {
self.prepare_for_estimation(&mut tx, saturate_variable_outputs)
.await?;
self._run(tx).await
}
pub async fn prepare_for_estimation(
&mut self,
tx: &mut fuel_tx::Script,
saturate_variable_outputs: bool,
) -> Result<()> {
let consensus_params = self.dry_runner.consensus_parameters().await?;
self.add_fake_witnesses(tx);
self.add_fake_coins(tx, &consensus_params);
if saturate_variable_outputs {
self.saturate_with_variable_outputs(tx, &consensus_params);
}
self.set_script_gas_limit_to_max(tx, &consensus_params);
Ok(())
}
pub fn last_dry_run(&self) -> Option<DryRun> {
self.last_dry_run
}
async fn _run(&mut self, tx: fuel_tx::Script) -> Result<DryRun> {
let dry_run = self.dry_runner.dry_run(tx.clone().into()).await?;
self.last_dry_run = Some(dry_run);
Ok(dry_run)
}
fn set_script_gas_limit_to_max(
&self,
tx: &mut fuel_tx::Script,
consensus_params: &ConsensusParameters,
) {
let max_gas = tx.max_gas(consensus_params.gas_costs(), consensus_params.fee_params()) + 1;
*tx.script_gas_limit_mut() = consensus_params.tx_params().max_gas_per_tx() - max_gas;
}
fn saturate_with_variable_outputs(
&self,
tx: &mut fuel_tx::Script,
consensus_params: &ConsensusParameters,
) {
let max_outputs = usize::from(consensus_params.tx_params().max_outputs());
let used_outputs = tx.outputs().len();
let unused_outputs = max_outputs.saturating_sub(used_outputs);
super::add_variable_outputs(tx, unused_outputs);
}
// When dry running a tx with `utxo_validation` off, the node will not validate signatures.
// However, the node will check if the right number of witnesses is present.
// This function will create witnesses from a default `Signature` such that the total length matches the expected one.
// Using a `Signature` ensures that the calculated fee includes the fee generated by the witnesses.
fn add_fake_witnesses(&self, tx: &mut fuel_tx::Script) {
let witness: Witness = Signature::default().as_ref().into();
let dry_run_witnesses: Vec<_> = repeat_n(witness, self.num_unresolved_witnesses).collect();
*tx.witnesses_mut() = [self.predefined_witnesses.clone(), dry_run_witnesses].concat();
}
fn add_fake_coins(&self, tx: &mut fuel_tx::Script, consensus_params: &ConsensusParameters) {
if let Some(fake_input) =
Self::needs_fake_base_input(tx.inputs(), consensus_params.base_asset_id())
{
tx.inputs_mut().push(fake_input);
// Add an empty `Witness` for the `coin_signed` we just added
tx.witnesses_mut().push(Witness::default());
tx.set_witness_limit(tx.witness_limit() + WITNESS_STATIC_SIZE as u64);
}
}
fn needs_fake_base_input(
inputs: &[FuelInput],
base_asset_id: &AssetId,
) -> Option<fuel_tx::Input> {
let has_base_asset = inputs.iter().any(|i| match i {
FuelInput::CoinSigned(CoinSigned { asset_id, .. })
| FuelInput::CoinPredicate(CoinPredicate { asset_id, .. })
if asset_id == base_asset_id =>
{
true
}
FuelInput::MessageCoinSigned(_) | FuelInput::MessageCoinPredicate(_) => true,
_ => false,
});
if has_base_asset {
return None;
}
let unique_owners = inputs
.iter()
.filter_map(|input| match input {
FuelInput::CoinSigned(CoinSigned { owner, .. })
| FuelInput::CoinPredicate(CoinPredicate { owner, .. }) => Some(owner),
_ => None,
})
.unique()
.collect::<Vec<_>>();
let fake_owner = if let [single_owner] = unique_owners.as_slice() {
**single_owner
} else {
Default::default()
};
Some(FuelInput::coin_signed(
Default::default(),
fake_owner,
1_000_000_000,
*base_asset_id,
TxPointer::default(),
0,
))
}
}
| rust | Apache-2.0 | 865e00c295de8b4a0a1ef7ac926c3c8266d5151b | 2026-01-04T15:31:59.450823Z | false |
FuelLabs/fuels-rs | https://github.com/FuelLabs/fuels-rs/blob/865e00c295de8b4a0a1ef7ac926c3c8266d5151b/packages/fuels-core/src/types/wrappers/node_info.rs | packages/fuels-core/src/types/wrappers/node_info.rs | #![cfg(feature = "std")]
use fuel_core_client::client::types::node_info::NodeInfo as ClientNodeInfo;
#[derive(Debug, Clone)]
pub struct NodeInfo {
pub utxo_validation: bool,
pub vm_backtrace: bool,
pub max_tx: u64,
pub max_depth: u64,
pub node_version: String,
}
impl From<ClientNodeInfo> for NodeInfo {
fn from(client_node_info: ClientNodeInfo) -> Self {
Self {
utxo_validation: client_node_info.utxo_validation,
vm_backtrace: client_node_info.vm_backtrace,
max_tx: client_node_info.max_tx,
max_depth: client_node_info.max_depth,
node_version: client_node_info.node_version,
}
}
}
| rust | Apache-2.0 | 865e00c295de8b4a0a1ef7ac926c3c8266d5151b | 2026-01-04T15:31:59.450823Z | false |
FuelLabs/fuels-rs | https://github.com/FuelLabs/fuels-rs/blob/865e00c295de8b4a0a1ef7ac926c3c8266d5151b/packages/fuels-core/src/types/wrappers/chain_info.rs | packages/fuels-core/src/types/wrappers/chain_info.rs | #![cfg(feature = "std")]
use fuel_core_client::client::types::chain_info::ChainInfo as ClientChainInfo;
use fuel_tx::ConsensusParameters;
use crate::types::block::Block;
#[derive(Debug)]
pub struct ChainInfo {
pub da_height: u64,
pub name: String,
pub latest_block: Block,
pub consensus_parameters: ConsensusParameters,
}
impl From<ClientChainInfo> for ChainInfo {
fn from(client_chain_info: ClientChainInfo) -> Self {
Self {
da_height: client_chain_info.da_height,
name: client_chain_info.name,
latest_block: client_chain_info.latest_block.into(),
consensus_parameters: client_chain_info.consensus_parameters,
}
}
}
| rust | Apache-2.0 | 865e00c295de8b4a0a1ef7ac926c3c8266d5151b | 2026-01-04T15:31:59.450823Z | false |
FuelLabs/fuels-rs | https://github.com/FuelLabs/fuels-rs/blob/865e00c295de8b4a0a1ef7ac926c3c8266d5151b/packages/fuels-core/src/types/wrappers/message_proof.rs | packages/fuels-core/src/types/wrappers/message_proof.rs | #![cfg(feature = "std")]
use fuel_core_client::client::types::{
MerkleProof as ClientMerkleProof, MessageProof as ClientMessageProof, primitives::Nonce,
};
use crate::types::{Address, Bytes32, block::Header};
#[derive(Debug)]
pub struct MerkleProof {
/// The proof set of the message proof.
pub proof_set: Vec<Bytes32>,
/// The index that was used to produce this proof.
pub proof_index: u64,
}
impl From<ClientMerkleProof> for MerkleProof {
fn from(client_merkle_proof: ClientMerkleProof) -> Self {
Self {
proof_set: client_merkle_proof.proof_set,
proof_index: client_merkle_proof.proof_index,
}
}
}
#[derive(Debug)]
pub struct MessageProof {
/// Proof that message is contained within the provided block header.
pub message_proof: MerkleProof,
/// Proof that the provided block header is contained within the blockchain history.
pub block_proof: MerkleProof,
/// The previous fuel block header that contains the message. Message block height <
/// commit block height.
pub message_block_header: Header,
/// The consensus header associated with the finalized commit being used
/// as the root of the block proof.
pub commit_block_header: Header,
pub sender: Address,
pub recipient: Address,
pub nonce: Nonce,
pub amount: u64,
pub data: Vec<u8>,
}
impl From<ClientMessageProof> for MessageProof {
fn from(client_message_proof: ClientMessageProof) -> Self {
Self {
message_proof: client_message_proof.message_proof.into(),
block_proof: client_message_proof.block_proof.into(),
message_block_header: client_message_proof.message_block_header.into(),
commit_block_header: client_message_proof.commit_block_header.into(),
sender: client_message_proof.sender,
recipient: client_message_proof.recipient,
nonce: client_message_proof.nonce,
amount: client_message_proof.amount,
data: client_message_proof.data,
}
}
}
| rust | Apache-2.0 | 865e00c295de8b4a0a1ef7ac926c3c8266d5151b | 2026-01-04T15:31:59.450823Z | false |
FuelLabs/fuels-rs | https://github.com/FuelLabs/fuels-rs/blob/865e00c295de8b4a0a1ef7ac926c3c8266d5151b/packages/fuels-core/src/types/wrappers/coin_type_id.rs | packages/fuels-core/src/types/wrappers/coin_type_id.rs | use fuel_tx::UtxoId;
use fuel_types::Nonce;
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum CoinTypeId {
UtxoId(UtxoId),
Nonce(Nonce),
}
| rust | Apache-2.0 | 865e00c295de8b4a0a1ef7ac926c3c8266d5151b | 2026-01-04T15:31:59.450823Z | false |
FuelLabs/fuels-rs | https://github.com/FuelLabs/fuels-rs/blob/865e00c295de8b4a0a1ef7ac926c3c8266d5151b/packages/fuels-core/src/types/wrappers/coin_type.rs | packages/fuels-core/src/types/wrappers/coin_type.rs | #![cfg(feature = "std")]
use fuel_core_client::client::types::CoinType as ClientCoinType;
use crate::types::{Address, AssetId, coin::Coin, coin_type_id::CoinTypeId, message::Message};
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum CoinType {
Coin(Coin),
Message(Message),
Unknown,
}
impl From<ClientCoinType> for CoinType {
fn from(client_resource: ClientCoinType) -> Self {
match client_resource {
ClientCoinType::Coin(coin) => CoinType::Coin(coin.into()),
ClientCoinType::MessageCoin(message) => CoinType::Message(message.into()),
ClientCoinType::Unknown => CoinType::Unknown,
}
}
}
impl CoinType {
pub fn id(&self) -> Option<CoinTypeId> {
match self {
CoinType::Coin(coin) => Some(CoinTypeId::UtxoId(coin.utxo_id)),
CoinType::Message(message) => Some(CoinTypeId::Nonce(message.nonce)),
CoinType::Unknown => None,
}
}
pub fn amount(&self) -> u64 {
match self {
CoinType::Coin(coin) => coin.amount,
CoinType::Message(message) => message.amount,
CoinType::Unknown => 0,
}
}
pub fn coin_asset_id(&self) -> Option<AssetId> {
match self {
CoinType::Coin(coin) => Some(coin.asset_id),
CoinType::Message(_) => None,
CoinType::Unknown => None,
}
}
pub fn asset_id(&self, base_asset_id: AssetId) -> Option<AssetId> {
match self {
CoinType::Coin(coin) => Some(coin.asset_id),
CoinType::Message(_) => Some(base_asset_id),
CoinType::Unknown => None,
}
}
pub fn owner(&self) -> Option<&Address> {
match self {
CoinType::Coin(coin) => Some(&coin.owner),
CoinType::Message(message) => Some(&message.recipient),
CoinType::Unknown => None,
}
}
}
| rust | Apache-2.0 | 865e00c295de8b4a0a1ef7ac926c3c8266d5151b | 2026-01-04T15:31:59.450823Z | false |
FuelLabs/fuels-rs | https://github.com/FuelLabs/fuels-rs/blob/865e00c295de8b4a0a1ef7ac926c3c8266d5151b/packages/fuels-core/src/types/wrappers/block.rs | packages/fuels-core/src/types/wrappers/block.rs | #![cfg(feature = "std")]
use chrono::{DateTime, Utc};
use fuel_core_client::client::types::{
block::{Block as ClientBlock, Header as ClientHeader},
primitives::Bytes32,
};
#[derive(Debug, Clone)]
pub struct Header {
pub id: Bytes32,
pub da_height: u64,
pub transactions_count: u16,
pub message_receipt_count: u32,
pub transactions_root: Bytes32,
pub message_outbox_root: Bytes32,
pub event_inbox_root: Bytes32,
pub consensus_parameters_version: u32,
pub state_transition_bytecode_version: u32,
pub height: u32,
pub prev_root: Bytes32,
pub time: Option<DateTime<Utc>>,
pub application_hash: Bytes32,
}
impl From<ClientHeader> for Header {
fn from(client_header: ClientHeader) -> Self {
let time = DateTime::from_timestamp(client_header.time.to_unix(), 0);
Self {
id: client_header.id,
da_height: client_header.da_height,
transactions_count: client_header.transactions_count,
message_receipt_count: client_header.message_receipt_count,
transactions_root: client_header.transactions_root,
message_outbox_root: client_header.message_outbox_root,
event_inbox_root: client_header.event_inbox_root,
consensus_parameters_version: client_header.consensus_parameters_version,
state_transition_bytecode_version: client_header.state_transition_bytecode_version,
height: client_header.height,
prev_root: client_header.prev_root,
time,
application_hash: client_header.application_hash,
}
}
}
#[derive(Debug, Clone)]
pub struct Block {
pub id: Bytes32,
pub header: Header,
pub transactions: Vec<Bytes32>,
}
impl From<ClientBlock> for Block {
fn from(client_block: ClientBlock) -> Self {
Self {
id: client_block.id,
header: client_block.header.into(),
transactions: client_block.transactions,
}
}
}
| rust | Apache-2.0 | 865e00c295de8b4a0a1ef7ac926c3c8266d5151b | 2026-01-04T15:31:59.450823Z | false |
FuelLabs/fuels-rs | https://github.com/FuelLabs/fuels-rs/blob/865e00c295de8b4a0a1ef7ac926c3c8266d5151b/packages/fuels-core/src/types/wrappers/transaction_response.rs | packages/fuels-core/src/types/wrappers/transaction_response.rs | #![cfg(feature = "std")]
use chrono::{DateTime, Utc};
use fuel_core_client::client::types::{
TransactionResponse as ClientTransactionResponse, TransactionStatus as ClientTransactionStatus,
TransactionType as ClientTxType,
};
use fuel_tx::Transaction;
use fuel_types::BlockHeight;
use crate::types::{transaction::TransactionType, tx_status::TxStatus};
#[derive(Debug, Clone)]
pub struct TransactionResponse {
pub transaction: TransactionType,
pub status: TxStatus,
pub block_height: Option<BlockHeight>,
pub time: Option<DateTime<Utc>>,
}
impl From<ClientTransactionResponse> for TransactionResponse {
fn from(client_response: ClientTransactionResponse) -> Self {
let block_height = match &client_response.status {
ClientTransactionStatus::Submitted { .. }
| ClientTransactionStatus::SqueezedOut { .. }
| ClientTransactionStatus::PreconfirmationSuccess { .. }
| ClientTransactionStatus::PreconfirmationFailure { .. } => None,
ClientTransactionStatus::Success { block_height, .. }
| ClientTransactionStatus::Failure { block_height, .. } => Some(*block_height),
};
let time = match &client_response.status {
ClientTransactionStatus::Submitted { .. }
| ClientTransactionStatus::SqueezedOut { .. }
| ClientTransactionStatus::PreconfirmationSuccess { .. }
| ClientTransactionStatus::PreconfirmationFailure { .. } => None,
ClientTransactionStatus::Success { time, .. }
| ClientTransactionStatus::Failure { time, .. } => {
DateTime::from_timestamp(time.to_unix(), 0)
}
};
let transaction = match client_response.transaction {
ClientTxType::Known(Transaction::Script(tx)) => TransactionType::Script(tx.into()),
ClientTxType::Known(Transaction::Create(tx)) => TransactionType::Create(tx.into()),
ClientTxType::Known(Transaction::Mint(tx)) => TransactionType::Mint(tx.into()),
ClientTxType::Known(Transaction::Upgrade(tx)) => TransactionType::Upgrade(tx.into()),
ClientTxType::Known(Transaction::Upload(tx)) => TransactionType::Upload(tx.into()),
ClientTxType::Known(Transaction::Blob(tx)) => TransactionType::Blob(tx.into()),
ClientTxType::Unknown => TransactionType::Unknown,
};
Self {
transaction,
status: client_response.status.into(),
block_height,
time,
}
}
}
| rust | Apache-2.0 | 865e00c295de8b4a0a1ef7ac926c3c8266d5151b | 2026-01-04T15:31:59.450823Z | false |
FuelLabs/fuels-rs | https://github.com/FuelLabs/fuels-rs/blob/865e00c295de8b4a0a1ef7ac926c3c8266d5151b/packages/fuels-core/src/types/wrappers/coin.rs | packages/fuels-core/src/types/wrappers/coin.rs | #![cfg(feature = "std")]
use fuel_core_chain_config::CoinConfig;
use fuel_core_client::client::types::{
coins::Coin as ClientCoin,
primitives::{AssetId, UtxoId},
};
use crate::types::Address;
#[derive(Debug, Clone, Default, PartialEq, Eq, Hash)]
pub struct Coin {
pub amount: u64,
pub asset_id: AssetId,
pub utxo_id: UtxoId,
pub owner: Address,
}
impl From<ClientCoin> for Coin {
fn from(coin: ClientCoin) -> Self {
Self {
amount: coin.amount,
asset_id: coin.asset_id,
utxo_id: coin.utxo_id,
owner: coin.owner,
}
}
}
impl From<Coin> for CoinConfig {
fn from(coin: Coin) -> CoinConfig {
Self {
tx_id: *coin.utxo_id.tx_id(),
output_index: coin.utxo_id.output_index(),
owner: fuel_core_chain_config::Owner::Address(coin.owner),
amount: coin.amount,
asset_id: coin.asset_id,
..Default::default()
}
}
}
| rust | Apache-2.0 | 865e00c295de8b4a0a1ef7ac926c3c8266d5151b | 2026-01-04T15:31:59.450823Z | false |
FuelLabs/fuels-rs | https://github.com/FuelLabs/fuels-rs/blob/865e00c295de8b4a0a1ef7ac926c3c8266d5151b/packages/fuels-core/src/types/wrappers/message.rs | packages/fuels-core/src/types/wrappers/message.rs | #![cfg(feature = "std")]
use crate::types::{Address, MessageId, Nonce};
use fuel_core_chain_config::MessageConfig;
use fuel_core_client::client::types::{
coins::MessageCoin as ClientMessageCoin, message::Message as ClientMessage,
};
#[derive(Debug, Clone, PartialEq, Eq, Hash, Default)]
pub enum MessageStatus {
#[default]
Unspent,
Spent,
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct Message {
pub amount: u64,
pub sender: Address,
pub recipient: Address,
pub nonce: Nonce,
pub data: Vec<u8>,
pub da_height: u64,
pub status: MessageStatus,
}
impl Message {
pub fn message_id(&self) -> MessageId {
fuel_tx::Input::compute_message_id(
&self.sender,
&self.recipient,
&self.nonce,
self.amount,
&self.data,
)
}
}
impl From<ClientMessage> for Message {
fn from(message: ClientMessage) -> Self {
Self {
amount: message.amount,
sender: message.sender,
recipient: message.recipient,
nonce: message.nonce,
data: message.data,
da_height: message.da_height,
status: MessageStatus::Unspent,
}
}
}
impl From<ClientMessageCoin> for Message {
fn from(message: ClientMessageCoin) -> Self {
Self {
amount: message.amount,
sender: message.sender,
recipient: message.recipient,
nonce: message.nonce,
data: Default::default(),
da_height: message.da_height,
status: MessageStatus::Unspent,
}
}
}
impl From<Message> for MessageConfig {
fn from(message: Message) -> MessageConfig {
MessageConfig {
sender: message.sender,
recipient: message.recipient,
nonce: message.nonce,
amount: message.amount,
data: message.data,
da_height: message.da_height.into(),
}
}
}
| rust | Apache-2.0 | 865e00c295de8b4a0a1ef7ac926c3c8266d5151b | 2026-01-04T15:31:59.450823Z | false |
FuelLabs/fuels-rs | https://github.com/FuelLabs/fuels-rs/blob/865e00c295de8b4a0a1ef7ac926c3c8266d5151b/packages/fuels-core/src/types/wrappers/input.rs | packages/fuels-core/src/types/wrappers/input.rs | #![cfg(feature = "std")]
use std::hash::Hash;
use fuel_tx::{TxPointer, UtxoId};
use fuel_types::{Bytes32, ContractId};
use crate::types::coin_type::CoinType;
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum Input {
ResourceSigned {
resource: CoinType,
},
ResourcePredicate {
resource: CoinType,
code: Vec<u8>,
data: Vec<u8>,
},
Contract {
utxo_id: UtxoId,
balance_root: Bytes32,
state_root: Bytes32,
tx_pointer: TxPointer,
contract_id: ContractId,
},
}
impl Input {
pub const fn resource_signed(resource: CoinType) -> Self {
Self::ResourceSigned { resource }
}
pub const fn resource_predicate(resource: CoinType, code: Vec<u8>, data: Vec<u8>) -> Self {
Self::ResourcePredicate {
resource,
code,
data,
}
}
pub fn amount(&self) -> Option<u64> {
match self {
Self::ResourceSigned { resource, .. } | Self::ResourcePredicate { resource, .. } => {
Some(resource.amount())
}
_ => None,
}
}
pub fn contains_data(&self) -> bool {
match self {
Self::ResourceSigned {
resource: CoinType::Message(msg),
..
}
| Self::ResourcePredicate {
resource: CoinType::Message(msg),
..
} => !msg.data.is_empty(),
_ => false,
}
}
pub const fn contract(
utxo_id: UtxoId,
balance_root: Bytes32,
state_root: Bytes32,
tx_pointer: TxPointer,
contract_id: ContractId,
) -> Self {
Self::Contract {
utxo_id,
balance_root,
state_root,
tx_pointer,
contract_id,
}
}
}
| rust | Apache-2.0 | 865e00c295de8b4a0a1ef7ac926c3c8266d5151b | 2026-01-04T15:31:59.450823Z | false |
FuelLabs/fuels-rs | https://github.com/FuelLabs/fuels-rs/blob/865e00c295de8b4a0a1ef7ac926c3c8266d5151b/packages/fuels-core/src/types/wrappers/transaction.rs | packages/fuels-core/src/types/wrappers/transaction.rs | use std::{collections::HashMap, fmt::Debug};
use async_trait::async_trait;
use fuel_crypto::{Message, Signature};
use fuel_tx::{
Blob, Bytes32, Cacheable, Chargeable, ConsensusParameters, Create, FormatValidityChecks, Input,
Mint, Output, Salt as FuelSalt, Script, StorageSlot, Transaction as FuelTransaction,
TransactionFee, UniqueIdentifier, Upgrade, Upload, Witness,
field::{
Inputs, MintAmount, MintAssetId, Outputs, Policies as PoliciesField, Script as ScriptField,
ScriptData, ScriptGasLimit, WitnessLimit, Witnesses,
},
input::{
coin::{CoinPredicate, CoinSigned},
message::{
MessageCoinPredicate, MessageCoinSigned, MessageDataPredicate, MessageDataSigned,
},
},
policies::PolicyType,
};
use fuel_types::{AssetId, ChainId, bytes::padded_len_usize};
use itertools::Itertools;
use crate::{
traits::Signer,
types::{
Address, DryRunner,
errors::{Error, Result, error, error_transaction},
},
utils::{calculate_witnesses_size, sealed},
};
#[derive(Default, Debug, Clone)]
pub struct Transactions {
fuel_transactions: Vec<FuelTransaction>,
}
impl Transactions {
pub fn new() -> Self {
Self::default()
}
pub fn insert(mut self, tx: impl Into<FuelTransaction>) -> Self {
self.fuel_transactions.push(tx.into());
self
}
pub fn as_slice(&self) -> &[FuelTransaction] {
&self.fuel_transactions
}
}
#[derive(Default, Debug, Clone, PartialEq, Eq)]
pub struct MintTransaction {
tx: Box<Mint>,
}
impl From<MintTransaction> for FuelTransaction {
fn from(mint: MintTransaction) -> Self {
(*mint.tx).into()
}
}
impl From<MintTransaction> for Mint {
fn from(tx: MintTransaction) -> Self {
*tx.tx
}
}
impl From<Mint> for MintTransaction {
fn from(tx: Mint) -> Self {
Self { tx: Box::new(tx) }
}
}
impl MintTransaction {
pub fn check_without_signatures(
&self,
block_height: u32,
consensus_parameters: &ConsensusParameters,
) -> Result<()> {
Ok(self
.tx
.check_without_signatures(block_height.into(), consensus_parameters)?)
}
#[must_use]
pub fn id(&self, chain_id: ChainId) -> Bytes32 {
self.tx.id(&chain_id)
}
#[must_use]
pub fn mint_asset_id(&self) -> &AssetId {
self.tx.mint_asset_id()
}
#[must_use]
pub fn mint_amount(&self) -> u64 {
*self.tx.mint_amount()
}
}
#[derive(Default, Debug, Copy, Clone)]
// ANCHOR: tx_policies_struct
pub struct TxPolicies {
tip: Option<u64>,
witness_limit: Option<u64>,
maturity: Option<u64>,
expiration: Option<u64>,
max_fee: Option<u64>,
script_gas_limit: Option<u64>,
owner: Option<u64>,
}
// ANCHOR_END: tx_policies_struct
impl TxPolicies {
pub fn new(
tip: Option<u64>,
witness_limit: Option<u64>,
maturity: Option<u64>,
expiration: Option<u64>,
max_fee: Option<u64>,
script_gas_limit: Option<u64>,
owner: Option<u64>,
) -> Self {
Self {
tip,
witness_limit,
maturity,
expiration,
max_fee,
script_gas_limit,
owner,
}
}
pub fn with_tip(mut self, tip: u64) -> Self {
self.tip = Some(tip);
self
}
pub fn tip(&self) -> Option<u64> {
self.tip
}
pub fn with_witness_limit(mut self, witness_limit: u64) -> Self {
self.witness_limit = Some(witness_limit);
self
}
pub fn witness_limit(&self) -> Option<u64> {
self.witness_limit
}
pub fn with_maturity(mut self, maturity: u64) -> Self {
self.maturity = Some(maturity);
self
}
pub fn maturity(&self) -> Option<u64> {
self.maturity
}
pub fn with_expiration(mut self, expiration: u64) -> Self {
self.expiration = Some(expiration);
self
}
pub fn expiration(&self) -> Option<u64> {
self.expiration
}
pub fn with_max_fee(mut self, max_fee: u64) -> Self {
self.max_fee = Some(max_fee);
self
}
pub fn max_fee(&self) -> Option<u64> {
self.max_fee
}
pub fn with_script_gas_limit(mut self, script_gas_limit: u64) -> Self {
self.script_gas_limit = Some(script_gas_limit);
self
}
pub fn script_gas_limit(&self) -> Option<u64> {
self.script_gas_limit
}
pub fn with_owner(mut self, owner: u64) -> Self {
self.owner = Some(owner);
self
}
pub fn owner(&self) -> Option<u64> {
self.owner
}
}
use fuel_tx::field::{BytecodeWitnessIndex, Salt, StorageSlots};
use crate::types::coin_type_id::CoinTypeId;
#[derive(Debug, Clone)]
pub enum TransactionType {
Script(ScriptTransaction),
Create(CreateTransaction),
Mint(MintTransaction),
Upload(UploadTransaction),
Upgrade(UpgradeTransaction),
Blob(BlobTransaction),
Unknown,
}
#[cfg_attr(target_arch = "wasm32", async_trait(?Send))]
#[cfg_attr(not(target_arch = "wasm32"), async_trait)]
pub trait EstimablePredicates: sealed::Sealed {
/// If a transaction contains predicates, we have to estimate them
/// before sending the transaction to the node. The estimation will check
/// all predicates and set the `predicate_gas_used` to the actual consumed gas.
async fn estimate_predicates(
&mut self,
provider: impl DryRunner,
latest_chain_executor_version: Option<u32>,
) -> Result<()>;
}
pub trait ValidatablePredicates: sealed::Sealed {
/// If a transaction contains predicates, we can verify that these predicates validate, ie
/// that they return `true`
fn validate_predicates(
self,
consensus_parameters: &ConsensusParameters,
block_height: u32,
) -> Result<()>;
}
#[cfg_attr(target_arch = "wasm32", async_trait(?Send))]
#[cfg_attr(not(target_arch = "wasm32"), async_trait)]
pub trait Transaction:
TryFrom<FuelTransaction, Error = Error>
+ Into<FuelTransaction>
+ EstimablePredicates
+ ValidatablePredicates
+ Clone
+ Debug
+ sealed::Sealed
{
fn fee_checked_from_tx(
&self,
consensus_parameters: &ConsensusParameters,
gas_price: u64,
) -> Option<TransactionFee>;
fn max_gas(&self, consensus_parameters: &ConsensusParameters) -> u64;
/// Performs all stateless transaction validity checks. This includes the validity
/// of fields according to rules in the specification and validity of signatures.
/// <https://github.com/FuelLabs/fuel-specs/blob/master/src/tx-format/transaction.md>
fn check(&self, block_height: u32, consensus_parameters: &ConsensusParameters) -> Result<()>;
fn id(&self, chain_id: ChainId) -> Bytes32;
fn maturity(&self) -> Option<u64>;
fn expiration(&self) -> Option<u64>;
fn owner(&self) -> Option<u64>;
fn metered_bytes_size(&self) -> usize;
fn inputs(&self) -> &Vec<Input>;
fn outputs(&self) -> &Vec<Output>;
fn witnesses(&self) -> &Vec<Witness>;
fn max_fee(&self) -> Option<u64>;
fn size(&self) -> usize;
fn witness_limit(&self) -> Option<u64>;
fn tip(&self) -> Option<u64>;
fn is_using_predicates(&self) -> bool;
/// Precompute transaction metadata. The metadata is required for
/// `check_without_signatures` validation.
fn precompute(&mut self, chain_id: &ChainId) -> Result<()>;
/// Append witness and return the corresponding witness index
fn append_witness(&mut self, witness: Witness) -> Result<usize>;
fn used_coins(&self, base_asset_id: &AssetId) -> HashMap<(Address, AssetId), Vec<CoinTypeId>>;
async fn sign_with(
&mut self,
signer: &(impl Signer + Send + Sync),
chain_id: ChainId,
) -> Result<Signature>;
}
impl TryFrom<TransactionType> for FuelTransaction {
type Error = Error;
fn try_from(value: TransactionType) -> Result<Self> {
match value {
TransactionType::Script(tx) => Ok(tx.into()),
TransactionType::Create(tx) => Ok(tx.into()),
TransactionType::Mint(tx) => Ok(tx.into()),
TransactionType::Upload(tx) => Ok(tx.into()),
TransactionType::Upgrade(tx) => Ok(tx.into()),
TransactionType::Blob(tx) => Ok(tx.into()),
TransactionType::Unknown => Err(error_transaction!(Other, "`Unknown` transaction")),
}
}
}
fn extract_coin_type_id(input: &Input) -> Option<CoinTypeId> {
if let Some(utxo_id) = input.utxo_id() {
return Some(CoinTypeId::UtxoId(*utxo_id));
} else if let Some(nonce) = input.nonce() {
return Some(CoinTypeId::Nonce(*nonce));
}
None
}
pub fn extract_owner_or_recipient(input: &Input) -> Option<Address> {
match input {
Input::CoinSigned(CoinSigned { owner, .. })
| Input::CoinPredicate(CoinPredicate { owner, .. }) => Some(*owner),
Input::MessageCoinSigned(MessageCoinSigned { recipient, .. })
| Input::MessageCoinPredicate(MessageCoinPredicate { recipient, .. })
| Input::MessageDataSigned(MessageDataSigned { recipient, .. })
| Input::MessageDataPredicate(MessageDataPredicate { recipient, .. }) => Some(*recipient),
Input::Contract(_) => None,
}
}
macro_rules! impl_tx_wrapper {
($wrapper: ident, $wrapped: ident) => {
#[derive(Debug, Clone)]
pub struct $wrapper {
pub(crate) tx: $wrapped,
pub(crate) is_using_predicates: bool,
}
impl From<$wrapper> for $wrapped {
fn from(tx: $wrapper) -> Self {
tx.tx
}
}
impl From<$wrapper> for FuelTransaction {
fn from(tx: $wrapper) -> Self {
tx.tx.into()
}
}
impl TryFrom<FuelTransaction> for $wrapper {
type Error = Error;
fn try_from(tx: FuelTransaction) -> Result<Self> {
match tx {
FuelTransaction::$wrapped(tx) => Ok(tx.into()),
_ => Err(error_transaction!(
Other,
"couldn't convert Transaction into a wrapper of type $wrapper"
)),
}
}
}
impl From<$wrapped> for $wrapper {
fn from(tx: $wrapped) -> Self {
let is_using_predicates = tx.inputs().iter().any(|input| {
matches!(
input,
Input::CoinPredicate { .. }
| Input::MessageCoinPredicate { .. }
| Input::MessageDataPredicate { .. }
)
});
$wrapper {
tx,
is_using_predicates,
}
}
}
impl ValidatablePredicates for $wrapper {
fn validate_predicates(
self,
_consensus_parameters: &ConsensusParameters,
_block_height: u32,
) -> Result<()> {
// Can no longer validate predicates locally due to the need for blob storage
Ok(())
}
}
impl sealed::Sealed for $wrapper {}
#[cfg_attr(target_arch = "wasm32", async_trait(?Send))]
#[cfg_attr(not(target_arch = "wasm32"), async_trait)]
impl Transaction for $wrapper {
fn max_gas(&self, consensus_parameters: &ConsensusParameters) -> u64 {
self.tx.max_gas(
consensus_parameters.gas_costs(),
consensus_parameters.fee_params(),
)
}
fn fee_checked_from_tx(
&self,
consensus_parameters: &ConsensusParameters,
gas_price: u64,
) -> Option<TransactionFee> {
TransactionFee::checked_from_tx(
&consensus_parameters.gas_costs(),
consensus_parameters.fee_params(),
&self.tx,
gas_price,
)
}
fn check(
&self,
block_height: u32,
consensus_parameters: &ConsensusParameters,
) -> Result<()> {
Ok(self.tx.check(block_height.into(), consensus_parameters)?)
}
fn id(&self, chain_id: ChainId) -> Bytes32 {
self.tx.id(&chain_id)
}
fn maturity(&self) -> Option<u64> {
self.tx.policies().get(PolicyType::Maturity)
}
fn expiration(&self) -> Option<u64> {
self.tx.policies().get(PolicyType::Expiration)
}
fn owner(&self) -> Option<u64> {
self.tx.policies().get(PolicyType::Owner)
}
fn metered_bytes_size(&self) -> usize {
self.tx.metered_bytes_size()
}
fn inputs(&self) -> &Vec<Input> {
self.tx.inputs()
}
fn outputs(&self) -> &Vec<Output> {
self.tx.outputs()
}
fn witnesses(&self) -> &Vec<Witness> {
self.tx.witnesses()
}
fn is_using_predicates(&self) -> bool {
self.is_using_predicates
}
fn precompute(&mut self, chain_id: &ChainId) -> Result<()> {
Ok(self.tx.precompute(chain_id)?)
}
fn max_fee(&self) -> Option<u64> {
self.tx.policies().get(PolicyType::MaxFee)
}
fn size(&self) -> usize {
use fuel_types::canonical::Serialize;
self.tx.size()
}
fn witness_limit(&self) -> Option<u64> {
self.tx.policies().get(PolicyType::WitnessLimit)
}
fn tip(&self) -> Option<u64> {
self.tx.policies().get(PolicyType::Tip)
}
fn append_witness(&mut self, witness: Witness) -> Result<usize> {
let witness_size = calculate_witnesses_size(
self.tx.witnesses().iter().chain(std::iter::once(&witness)),
);
let new_witnesses_size = padded_len_usize(witness_size)
.ok_or_else(|| error!(Other, "witness size overflow: {witness_size}"))?
as u64;
if new_witnesses_size > self.tx.witness_limit() {
Err(error_transaction!(
Validation,
"Witness limit exceeded. Consider setting the limit manually with \
a transaction builder. The new limit should be: `{new_witnesses_size}`"
))
} else {
let idx = self.tx.witnesses().len();
self.tx.witnesses_mut().push(witness);
Ok(idx)
}
}
fn used_coins(
&self,
base_asset_id: &AssetId,
) -> HashMap<(Address, AssetId), Vec<CoinTypeId>> {
self.inputs()
.iter()
.filter_map(|input| match input {
Input::Contract { .. } => None,
_ => {
// Not a contract, it's safe to expect.
let owner = extract_owner_or_recipient(input).expect("has owner");
let asset_id = input
.asset_id(base_asset_id)
.expect("has `asset_id`")
.to_owned();
let id = extract_coin_type_id(input).unwrap();
Some(((owner, asset_id), id))
}
})
.into_group_map()
}
async fn sign_with(
&mut self,
signer: &(impl Signer + Send + Sync),
chain_id: ChainId,
) -> Result<Signature> {
let tx_id = self.id(chain_id);
let message = Message::from_bytes(*tx_id);
let signature = signer.sign(message).await?;
self.append_witness(signature.as_ref().into())?;
Ok(signature)
}
}
};
}
impl_tx_wrapper!(ScriptTransaction, Script);
impl_tx_wrapper!(CreateTransaction, Create);
impl_tx_wrapper!(UploadTransaction, Upload);
impl_tx_wrapper!(UpgradeTransaction, Upgrade);
impl_tx_wrapper!(BlobTransaction, Blob);
#[cfg_attr(target_arch = "wasm32", async_trait(?Send))]
#[cfg_attr(not(target_arch = "wasm32"), async_trait)]
impl EstimablePredicates for UploadTransaction {
async fn estimate_predicates(
&mut self,
provider: impl DryRunner,
latest_chain_executor_version: Option<u32>,
) -> Result<()> {
let tx = provider
.estimate_predicates(&self.tx.clone().into(), latest_chain_executor_version)
.await?;
tx.as_upload().expect("is upload").clone_into(&mut self.tx);
Ok(())
}
}
#[cfg_attr(target_arch = "wasm32", async_trait(?Send))]
#[cfg_attr(not(target_arch = "wasm32"), async_trait)]
impl EstimablePredicates for UpgradeTransaction {
async fn estimate_predicates(
&mut self,
provider: impl DryRunner,
latest_chain_executor_version: Option<u32>,
) -> Result<()> {
let tx = provider
.estimate_predicates(&self.tx.clone().into(), latest_chain_executor_version)
.await?;
tx.as_upgrade()
.expect("is upgrade")
.clone_into(&mut self.tx);
Ok(())
}
}
#[cfg_attr(target_arch = "wasm32", async_trait(?Send))]
#[cfg_attr(not(target_arch = "wasm32"), async_trait)]
impl EstimablePredicates for CreateTransaction {
async fn estimate_predicates(
&mut self,
provider: impl DryRunner,
latest_chain_executor_version: Option<u32>,
) -> Result<()> {
let tx = provider
.estimate_predicates(&self.tx.clone().into(), latest_chain_executor_version)
.await?;
tx.as_create().expect("is create").clone_into(&mut self.tx);
Ok(())
}
}
impl CreateTransaction {
pub fn salt(&self) -> &FuelSalt {
self.tx.salt()
}
pub fn bytecode_witness_index(&self) -> u16 {
*self.tx.bytecode_witness_index()
}
pub fn storage_slots(&self) -> &Vec<StorageSlot> {
self.tx.storage_slots()
}
}
#[cfg_attr(target_arch = "wasm32", async_trait(?Send))]
#[cfg_attr(not(target_arch = "wasm32"), async_trait)]
impl EstimablePredicates for ScriptTransaction {
async fn estimate_predicates(
&mut self,
provider: impl DryRunner,
latest_chain_executor_version: Option<u32>,
) -> Result<()> {
let tx = provider
.estimate_predicates(&self.tx.clone().into(), latest_chain_executor_version)
.await?;
tx.as_script().expect("is script").clone_into(&mut self.tx);
Ok(())
}
}
#[cfg_attr(target_arch = "wasm32", async_trait(?Send))]
#[cfg_attr(not(target_arch = "wasm32"), async_trait)]
impl EstimablePredicates for BlobTransaction {
async fn estimate_predicates(
&mut self,
provider: impl DryRunner,
latest_chain_executor_version: Option<u32>,
) -> Result<()> {
let tx = provider
.estimate_predicates(&self.tx.clone().into(), latest_chain_executor_version)
.await?;
tx.as_blob().expect("is blob").clone_into(&mut self.tx);
Ok(())
}
}
impl ScriptTransaction {
pub fn script(&self) -> &Vec<u8> {
self.tx.script()
}
pub fn script_data(&self) -> &Vec<u8> {
self.tx.script_data()
}
pub fn gas_limit(&self) -> u64 {
*self.tx.script_gas_limit()
}
pub fn with_gas_limit(mut self, gas_limit: u64) -> Self {
*self.tx.script_gas_limit_mut() = gas_limit;
self
}
}
#[cfg(test)]
mod test {
use fuel_tx::policies::Policies;
use super::*;
#[test]
fn append_witnesses_returns_error_when_limit_exceeded() {
let mut tx = ScriptTransaction {
tx: FuelTransaction::script(
0,
vec![],
vec![],
Policies::default(),
vec![],
vec![],
vec![],
),
is_using_predicates: false,
};
let witness = vec![0, 1, 2].into();
let err = tx.append_witness(witness).expect_err("should error");
let expected_err_str = "transaction validation: Witness limit exceeded. \
Consider setting the limit manually with a transaction builder. \
The new limit should be: `16`";
assert_eq!(&err.to_string(), expected_err_str);
}
}
| rust | Apache-2.0 | 865e00c295de8b4a0a1ef7ac926c3c8266d5151b | 2026-01-04T15:31:59.450823Z | false |
FuelLabs/fuels-rs | https://github.com/FuelLabs/fuels-rs/blob/865e00c295de8b4a0a1ef7ac926c3c8266d5151b/packages/fuels-core/src/types/core/bytes.rs | packages/fuels-core/src/types/core/bytes.rs | use crate::types::errors::Result;
#[derive(Debug, PartialEq, Clone, Eq)]
pub struct Bytes(pub Vec<u8>);
impl Bytes {
/// Create a new `Bytes` from a string representation of a hex.
/// Accepts both `0x` prefixed and non-prefixed hex strings.
pub fn from_hex_str(hex: &str) -> Result<Self> {
let hex = if let Some(stripped_hex) = hex.strip_prefix("0x") {
stripped_hex
} else {
hex
};
let bytes = hex::decode(hex)?;
Ok(Bytes(bytes))
}
}
impl From<Bytes> for Vec<u8> {
fn from(bytes: Bytes) -> Vec<u8> {
bytes.0
}
}
impl PartialEq<Vec<u8>> for Bytes {
fn eq(&self, other: &Vec<u8>) -> bool {
self.0 == *other
}
}
impl PartialEq<Bytes> for Vec<u8> {
fn eq(&self, other: &Bytes) -> bool {
*self == other.0
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn from_hex_str_b256() -> Result<()> {
// ANCHOR: bytes_from_hex_str
let hex_str = "0101010101010101010101010101010101010101010101010101010101010101";
let bytes = Bytes::from_hex_str(hex_str)?;
assert_eq!(bytes.0, vec![1u8; 32]);
// With the `0x0` prefix
// ANCHOR: hex_string_to_bytes32
let hex_str = "0x0101010101010101010101010101010101010101010101010101010101010101";
let bytes = Bytes::from_hex_str(hex_str)?;
// ANCHOR_END: hex_string_to_bytes32
assert_eq!(bytes.0, vec![1u8; 32]);
// ANCHOR_END: bytes_from_hex_str
Ok(())
}
}
| rust | Apache-2.0 | 865e00c295de8b4a0a1ef7ac926c3c8266d5151b | 2026-01-04T15:31:59.450823Z | false |
FuelLabs/fuels-rs | https://github.com/FuelLabs/fuels-rs/blob/865e00c295de8b4a0a1ef7ac926c3c8266d5151b/packages/fuels-core/src/types/core/bits.rs | packages/fuels-core/src/types/core/bits.rs | use fuel_tx::SubAssetId;
use fuel_types::AssetId;
use fuels_macros::{Parameterize, Tokenizable, TryFrom};
use crate::types::errors::Result;
// A simple wrapper around [u8; 32] representing the `b256` type. Exists
// mainly so that we may differentiate `Parameterize` and `Tokenizable`
// implementations from what otherwise is just an array of 32 u8's.
#[derive(Debug, PartialEq, Eq, Copy, Clone)]
pub struct Bits256(pub [u8; 32]);
impl Bits256 {
/// Returns `Self` with zeroes inside.
pub fn zeroed() -> Self {
Self([0; 32])
}
/// Create a new `Bits256` from a string representation of a hex.
/// Accepts both `0x` prefixed and non-prefixed hex strings.
pub fn from_hex_str(hex: &str) -> Result<Self> {
let hex = if let Some(stripped_hex) = hex.strip_prefix("0x") {
stripped_hex
} else {
hex
};
let mut bytes = [0u8; 32];
hex::decode_to_slice(hex, &mut bytes as &mut [u8])?;
Ok(Bits256(bytes))
}
}
impl From<AssetId> for Bits256 {
fn from(value: AssetId) -> Self {
Self(value.into())
}
}
impl From<SubAssetId> for Bits256 {
fn from(value: SubAssetId) -> Self {
Self(value.into())
}
}
// A simple wrapper around [Bits256; 2] representing the `B512` type.
#[derive(Debug, PartialEq, Eq, Copy, Clone, Parameterize, Tokenizable, TryFrom)]
#[FuelsCorePath = "crate"]
#[FuelsTypesPath = "crate::types"]
// ANCHOR: b512
pub struct B512 {
pub bytes: [Bits256; 2],
}
// ANCHOR_END: b512
impl From<(Bits256, Bits256)> for B512 {
fn from(bits_tuple: (Bits256, Bits256)) -> Self {
B512 {
bytes: [bits_tuple.0, bits_tuple.1],
}
}
}
#[derive(Debug, PartialEq, Eq, Copy, Clone, Parameterize, Tokenizable, TryFrom)]
#[FuelsCorePath = "crate"]
#[FuelsTypesPath = "crate::types"]
// ANCHOR: evm_address
pub struct EvmAddress {
// An evm address is only 20 bytes, the first 12 bytes should be set to 0
value: Bits256,
}
// ANCHOR_END: evm_address
impl EvmAddress {
fn new(b256: Bits256) -> Self {
Self {
value: Bits256(Self::clear_12_bytes(b256.0)),
}
}
pub fn value(&self) -> Bits256 {
self.value
}
// sets the leftmost 12 bytes to zero
fn clear_12_bytes(bytes: [u8; 32]) -> [u8; 32] {
let mut bytes = bytes;
bytes[..12].copy_from_slice(&[0u8; 12]);
bytes
}
}
impl From<Bits256> for EvmAddress {
fn from(b256: Bits256) -> Self {
EvmAddress::new(b256)
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{
traits::{Parameterize, Tokenizable},
types::{Token, param_types::ParamType},
};
#[test]
fn from_hex_str_b256() -> Result<()> {
// ANCHOR: from_hex_str
let hex_str = "0101010101010101010101010101010101010101010101010101010101010101";
let bits256 = Bits256::from_hex_str(hex_str)?;
assert_eq!(bits256.0, [1u8; 32]);
// With the `0x0` prefix
// ANCHOR: hex_str_to_bits256
let hex_str = "0x0101010101010101010101010101010101010101010101010101010101010101";
let bits256 = Bits256::from_hex_str(hex_str)?;
// ANCHOR_END: hex_str_to_bits256
assert_eq!(bits256.0, [1u8; 32]);
// ANCHOR_END: from_hex_str
Ok(())
}
#[test]
fn test_param_type_evm_addr() {
assert_eq!(
EvmAddress::param_type(),
ParamType::Struct {
name: "EvmAddress".to_string(),
fields: vec![("value".to_string(), ParamType::B256)],
generics: vec![]
}
);
}
#[test]
fn evm_address_clears_first_12_bytes() -> Result<()> {
let data = [1u8; 32];
let address = EvmAddress::new(Bits256(data));
let expected_data = Bits256([
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1,
]);
assert_eq!(address.value(), expected_data);
Ok(())
}
#[test]
fn test_into_token_evm_addr() {
let bits = [1u8; 32];
let evm_address = EvmAddress::from(Bits256(bits));
let token = evm_address.into_token();
let expected_data = [
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1,
];
assert_eq!(token, Token::Struct(vec![Token::B256(expected_data)]));
}
}
| rust | Apache-2.0 | 865e00c295de8b4a0a1ef7ac926c3c8266d5151b | 2026-01-04T15:31:59.450823Z | false |
FuelLabs/fuels-rs | https://github.com/FuelLabs/fuels-rs/blob/865e00c295de8b4a0a1ef7ac926c3c8266d5151b/packages/fuels-core/src/types/core/raw_slice.rs | packages/fuels-core/src/types/core/raw_slice.rs | #[derive(Debug, PartialEq, Clone, Eq)]
pub struct RawSlice(pub Vec<u8>);
impl From<RawSlice> for Vec<u8> {
fn from(raw_slice: RawSlice) -> Vec<u8> {
raw_slice.0
}
}
impl PartialEq<Vec<u8>> for RawSlice {
fn eq(&self, other: &Vec<u8>) -> bool {
self.0 == *other
}
}
impl PartialEq<RawSlice> for Vec<u8> {
fn eq(&self, other: &RawSlice) -> bool {
*self == other.0
}
}
| rust | Apache-2.0 | 865e00c295de8b4a0a1ef7ac926c3c8266d5151b | 2026-01-04T15:31:59.450823Z | false |
FuelLabs/fuels-rs | https://github.com/FuelLabs/fuels-rs/blob/865e00c295de8b4a0a1ef7ac926c3c8266d5151b/packages/fuels-core/src/types/core/u256.rs | packages/fuels-core/src/types/core/u256.rs | #![allow(clippy::assign_op_pattern)]
#![allow(clippy::manual_div_ceil)]
use serde::{Deserialize, Deserializer, Serialize, Serializer, de};
use uint::construct_uint;
use crate::{
traits::{Parameterize, Tokenizable},
types::{
Token,
errors::{Result as FuelsResult, error},
param_types::ParamType,
},
};
construct_uint! {
pub struct U256(4);
}
impl Parameterize for U256 {
fn param_type() -> ParamType {
ParamType::U256
}
}
impl Tokenizable for U256 {
fn from_token(token: Token) -> FuelsResult<Self>
where
Self: Sized,
{
match token {
Token::U256(data) => Ok(data),
_ => Err(error!(
Other,
"`U256` cannot be constructed from token `{token}`"
)),
}
}
fn into_token(self) -> Token {
Token::U256(self)
}
}
impl Serialize for U256 {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
serializer.serialize_str(&self.to_string())
}
}
impl<'de> Deserialize<'de> for U256 {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
U256::from_dec_str(Deserialize::deserialize(deserializer)?).map_err(de::Error::custom)
}
}
#[cfg(test)]
mod tests {
use crate::types::U256;
#[test]
fn u256_serialize_deserialize() {
let num = U256::from(123);
let serialized: String = serde_json::to_string(&num).unwrap();
assert_eq!(serialized, "\"123\"");
let deserialized_num: U256 = serde_json::from_str(&serialized).unwrap();
assert_eq!(deserialized_num, num);
}
}
| rust | Apache-2.0 | 865e00c295de8b4a0a1ef7ac926c3c8266d5151b | 2026-01-04T15:31:59.450823Z | false |
FuelLabs/fuels-rs | https://github.com/FuelLabs/fuels-rs/blob/865e00c295de8b4a0a1ef7ac926c3c8266d5151b/packages/fuels-core/src/types/core/identity.rs | packages/fuels-core/src/types/core/identity.rs | use fuel_types::{Address, ContractId};
use fuels_macros::{Parameterize, Tokenizable, TryFrom};
use serde::{Deserialize, Serialize};
#[derive(
Debug,
Copy,
Clone,
PartialEq,
Eq,
Hash,
Parameterize,
Tokenizable,
TryFrom,
Serialize,
Deserialize,
)]
#[FuelsCorePath = "crate"]
#[FuelsTypesPath = "crate::types"]
pub enum Identity {
Address(Address),
ContractId(ContractId),
}
impl Default for Identity {
fn default() -> Self {
Self::Address(Address::default())
}
}
impl AsRef<[u8]> for Identity {
fn as_ref(&self) -> &[u8] {
match self {
Identity::Address(address) => address.as_ref(),
Identity::ContractId(contract_id) => contract_id.as_ref(),
}
}
}
impl From<&Address> for Identity {
fn from(address: &Address) -> Self {
Self::Address(*address)
}
}
impl From<Address> for Identity {
fn from(address: Address) -> Self {
Self::Address(address)
}
}
impl From<&ContractId> for Identity {
fn from(contract_id: &ContractId) -> Self {
Self::ContractId(*contract_id)
}
}
impl From<ContractId> for Identity {
fn from(contract_id: ContractId) -> Self {
Self::ContractId(contract_id)
}
}
| rust | Apache-2.0 | 865e00c295de8b4a0a1ef7ac926c3c8266d5151b | 2026-01-04T15:31:59.450823Z | false |
FuelLabs/fuels-rs | https://github.com/FuelLabs/fuels-rs/blob/865e00c295de8b4a0a1ef7ac926c3c8266d5151b/packages/fuels-core/src/types/core/sized_ascii_string.rs | packages/fuels-core/src/types/core/sized_ascii_string.rs | use std::fmt::{Debug, Display, Formatter};
use serde::{Deserialize, Serialize};
use crate::types::errors::{Error, Result, error};
// To be used when interacting with contracts which have string slices in their ABI.
// The FuelVM strings only support ascii characters.
#[derive(Debug, PartialEq, Clone, Eq)]
pub struct AsciiString {
data: String,
}
impl AsciiString {
pub fn new(data: String) -> Result<Self> {
if !data.is_ascii() {
return Err(error!(
Other,
"`AsciiString` must be constructed from a string containing only ascii encodable characters. Got: `{data}`"
));
}
Ok(Self { data })
}
pub fn to_trimmed_str(&self) -> &str {
self.data.trim()
}
pub fn to_left_trimmed_str(&self) -> &str {
self.data.trim_start()
}
pub fn to_right_trimmed_str(&self) -> &str {
self.data.trim_end()
}
}
impl TryFrom<&str> for AsciiString {
type Error = Error;
fn try_from(value: &str) -> Result<Self> {
Self::new(value.to_owned())
}
}
impl TryFrom<String> for AsciiString {
type Error = Error;
fn try_from(value: String) -> Result<Self> {
Self::new(value)
}
}
impl From<AsciiString> for String {
fn from(ascii_str: AsciiString) -> Self {
ascii_str.data
}
}
impl<const LEN: usize> AsRef<str> for SizedAsciiString<LEN> {
fn as_ref(&self) -> &str {
&self.data
}
}
impl Display for AsciiString {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.data)
}
}
impl PartialEq<&str> for AsciiString {
fn eq(&self, other: &&str) -> bool {
self.data == *other
}
}
impl PartialEq<AsciiString> for &str {
fn eq(&self, other: &AsciiString) -> bool {
*self == other.data
}
}
// To be used when interacting with contracts which have strings in their ABI.
// The length of a string is part of its type -- i.e. str[2] is a
// different type from str[3]. The FuelVM strings only support ascii characters.
#[derive(Debug, PartialEq, Clone, Eq, Hash, Default)]
pub struct SizedAsciiString<const LEN: usize> {
data: String,
}
impl<const LEN: usize> SizedAsciiString<LEN> {
pub fn new(data: String) -> Result<Self> {
if !data.is_ascii() {
return Err(error!(
Other,
"`SizedAsciiString` must be constructed from a `String` containing only ascii encodable characters. Got: `{data}`"
));
}
if data.len() != LEN {
return Err(error!(
Other,
"`SizedAsciiString<{LEN}>` must be constructed from a `String` of length {LEN}. Got: `{data}`"
));
}
Ok(Self { data })
}
pub fn to_trimmed_str(&self) -> &str {
self.data.trim()
}
pub fn to_left_trimmed_str(&self) -> &str {
self.data.trim_start()
}
pub fn to_right_trimmed_str(&self) -> &str {
self.data.trim_end()
}
/// Pad `data` string with whitespace characters on the right to fit into the `SizedAsciiString`
pub fn new_with_right_whitespace_padding(data: String) -> Result<Self> {
if data.len() > LEN {
return Err(error!(
Other,
"`SizedAsciiString<{LEN}>` cannot be constructed from a string of size {}",
data.len()
));
}
Ok(Self {
data: format!("{:LEN$}", data),
})
}
}
impl<const LEN: usize> TryFrom<&str> for SizedAsciiString<LEN> {
type Error = Error;
fn try_from(value: &str) -> Result<Self> {
Self::new(value.to_owned())
}
}
impl<const LEN: usize> TryFrom<String> for SizedAsciiString<LEN> {
type Error = Error;
fn try_from(value: String) -> Result<Self> {
Self::new(value)
}
}
impl<const LEN: usize> From<SizedAsciiString<LEN>> for String {
fn from(sized_ascii_str: SizedAsciiString<LEN>) -> Self {
sized_ascii_str.data
}
}
impl<const LEN: usize> Display for SizedAsciiString<LEN> {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.data)
}
}
impl<const LEN: usize> PartialEq<&str> for SizedAsciiString<LEN> {
fn eq(&self, other: &&str) -> bool {
self.data == *other
}
}
impl<const LEN: usize> PartialEq<SizedAsciiString<LEN>> for &str {
fn eq(&self, other: &SizedAsciiString<LEN>) -> bool {
*self == other.data
}
}
impl<const LEN: usize> Serialize for SizedAsciiString<LEN> {
fn serialize<S: serde::Serializer>(
&self,
serializer: S,
) -> core::result::Result<S::Ok, S::Error> {
self.data.serialize(serializer)
}
}
impl<'de, const LEN: usize> Deserialize<'de> for SizedAsciiString<LEN> {
fn deserialize<D: serde::Deserializer<'de>>(
deserializer: D,
) -> core::result::Result<Self, D::Error> {
let data = String::deserialize(deserializer)?;
Self::new(data).map_err(serde::de::Error::custom)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn accepts_ascii_of_correct_length() {
// ANCHOR: string_simple_example
let ascii_data = "abc".to_string();
SizedAsciiString::<3>::new(ascii_data)
.expect("should have succeeded since we gave ascii data of correct length!");
// ANCHOR_END: string_simple_example
}
#[test]
fn refuses_non_ascii() {
let ascii_data = "ab©".to_string();
let err = SizedAsciiString::<3>::new(ascii_data)
.expect_err("should not have succeeded since we gave non ascii data");
let expected_reason = "`SizedAsciiString` must be constructed from a `String` containing only ascii encodable characters. Got: ";
assert!(matches!(err, Error::Other(reason) if reason.starts_with(expected_reason)));
}
#[test]
fn refuses_invalid_len() {
let ascii_data = "abcd".to_string();
let err = SizedAsciiString::<3>::new(ascii_data)
.expect_err("should not have succeeded since we gave data of wrong length");
let expected_reason =
"`SizedAsciiString<3>` must be constructed from a `String` of length 3. Got: `abcd`";
assert!(matches!(err, Error::Other(reason) if reason.starts_with(expected_reason)));
}
// ANCHOR: conversion
#[test]
fn can_be_constructed_from_str_ref() {
let _: SizedAsciiString<3> = "abc".try_into().expect("should have succeeded");
}
#[test]
fn can_be_constructed_from_string() {
let _: SizedAsciiString<3> = "abc".to_string().try_into().expect("should have succeeded");
}
#[test]
fn can_be_converted_into_string() {
let sized_str = SizedAsciiString::<3>::new("abc".to_string()).unwrap();
let str: String = sized_str.into();
assert_eq!(str, "abc");
}
// ANCHOR_END: conversion
#[test]
fn can_be_printed() {
let sized_str = SizedAsciiString::<3>::new("abc".to_string()).unwrap();
assert_eq!(sized_str.to_string(), "abc");
}
#[test]
fn can_be_compared_w_str_ref() {
let sized_str = SizedAsciiString::<3>::new("abc".to_string()).unwrap();
assert_eq!(sized_str, "abc");
// and vice-versa
assert_eq!("abc", sized_str);
}
#[test]
fn trim() -> Result<()> {
// Using single whitespaces
let untrimmed = SizedAsciiString::<9>::new(" est abc ".to_string())?;
assert_eq!("est abc ", untrimmed.to_left_trimmed_str());
assert_eq!(" est abc", untrimmed.to_right_trimmed_str());
assert_eq!("est abc", untrimmed.to_trimmed_str());
let padded = // adds 6 whitespaces
SizedAsciiString::<12>::new_with_right_whitespace_padding("victor".to_string())?;
assert_eq!("victor ", padded);
Ok(())
}
#[test]
fn test_can_serialize_sized_ascii() {
let sized_str = SizedAsciiString::<3>::new("abc".to_string()).unwrap();
let serialized = serde_json::to_string(&sized_str).unwrap();
assert_eq!(serialized, "\"abc\"");
}
#[test]
fn test_can_deserialize_sized_ascii() {
let serialized = "\"abc\"";
let deserialized: SizedAsciiString<3> = serde_json::from_str(serialized).unwrap();
assert_eq!(
deserialized,
SizedAsciiString::<3>::new("abc".to_string()).unwrap()
);
}
#[test]
fn test_can_convert_sized_ascii_to_bytes() {
let sized_str = SizedAsciiString::<3>::new("abc".to_string()).unwrap();
let bytes: &[u8] = sized_str.as_ref().as_bytes();
assert_eq!(bytes, &[97, 98, 99]);
}
}
| rust | Apache-2.0 | 865e00c295de8b4a0a1ef7ac926c3c8266d5151b | 2026-01-04T15:31:59.450823Z | false |
FuelLabs/fuels-rs | https://github.com/FuelLabs/fuels-rs/blob/865e00c295de8b4a0a1ef7ac926c3c8266d5151b/packages/fuels-core/src/traits/signer.rs | packages/fuels-core/src/traits/signer.rs | use async_trait::async_trait;
use auto_impl::auto_impl;
use fuel_crypto::{Message, Signature};
use crate::types::{Address, errors::Result};
/// Trait for signing transactions and messages
///
/// Implement this trait to support different signing modes, e.g. hardware wallet, hosted etc.
#[cfg_attr(target_arch = "wasm32", async_trait(?Send))]
#[cfg_attr(not(target_arch = "wasm32"), async_trait)]
#[auto_impl(&, Box, Rc, Arc)]
pub trait Signer {
async fn sign(&self, message: Message) -> Result<Signature>;
fn address(&self) -> Address;
}
| rust | Apache-2.0 | 865e00c295de8b4a0a1ef7ac926c3c8266d5151b | 2026-01-04T15:31:59.450823Z | false |
FuelLabs/fuels-rs | https://github.com/FuelLabs/fuels-rs/blob/865e00c295de8b4a0a1ef7ac926c3c8266d5151b/packages/fuels-core/src/traits/tokenizable.rs | packages/fuels-core/src/traits/tokenizable.rs | use fuel_types::{Address, AssetId, ContractId};
use crate::{
traits::Parameterize,
types::{
AsciiString, Bits256, Bytes, RawSlice, SizedAsciiString, StaticStringToken, Token,
errors::{Result, error},
param_types::ParamType,
},
};
pub trait Tokenizable {
/// Converts a `Token` into expected type.
fn from_token(token: Token) -> Result<Self>
where
Self: Sized;
/// Converts a specified type back into token.
fn into_token(self) -> Token;
}
impl Tokenizable for Token {
fn from_token(token: Token) -> Result<Self> {
Ok(token)
}
fn into_token(self) -> Token {
self
}
}
impl Tokenizable for Bits256 {
fn from_token(token: Token) -> Result<Self>
where
Self: Sized,
{
match token {
Token::B256(data) => Ok(Bits256(data)),
_ => Err(error!(
Other,
"`Bits256` cannot be constructed from token {token}"
)),
}
}
fn into_token(self) -> Token {
Token::B256(self.0)
}
}
impl<T: Tokenizable> Tokenizable for Vec<T> {
fn from_token(token: Token) -> Result<Self>
where
Self: Sized,
{
if let Token::Vector(tokens) = token {
tokens.into_iter().map(Tokenizable::from_token).collect()
} else {
Err(error!(
Other,
"`Vec::from_token` must only be given a `Token::Vector`. Got: `{token}`"
))
}
}
fn into_token(self) -> Token {
let tokens = self.into_iter().map(Tokenizable::into_token).collect();
Token::Vector(tokens)
}
}
impl Tokenizable for bool {
fn from_token(token: Token) -> Result<Self> {
match token {
Token::Bool(data) => Ok(data),
other => Err(error!(Other, "expected `bool`, got `{:?}`", other)),
}
}
fn into_token(self) -> Token {
Token::Bool(self)
}
}
impl Tokenizable for () {
fn from_token(token: Token) -> Result<Self>
where
Self: Sized,
{
match token {
Token::Unit => Ok(()),
other => Err(error!(Other, "expected `Unit`, got `{:?}`", other)),
}
}
fn into_token(self) -> Token {
Token::Unit
}
}
impl Tokenizable for u8 {
fn from_token(token: Token) -> Result<Self> {
match token {
Token::U8(data) => Ok(data),
other => Err(error!(Other, "expected `u8`, got `{:?}`", other)),
}
}
fn into_token(self) -> Token {
Token::U8(self)
}
}
impl Tokenizable for u16 {
fn from_token(token: Token) -> Result<Self> {
match token {
Token::U16(data) => Ok(data),
other => Err(error!(Other, "expected `u16`, got `{:?}`", other)),
}
}
fn into_token(self) -> Token {
Token::U16(self)
}
}
impl Tokenizable for u32 {
fn from_token(token: Token) -> Result<Self> {
match token {
Token::U32(data) => Ok(data),
other => Err(error!(Other, "expected `u32`, got {:?}", other)),
}
}
fn into_token(self) -> Token {
Token::U32(self)
}
}
impl Tokenizable for u64 {
fn from_token(token: Token) -> Result<Self> {
match token {
Token::U64(data) => Ok(data),
other => Err(error!(Other, "expected `u64`, got {:?}", other)),
}
}
fn into_token(self) -> Token {
Token::U64(self)
}
}
impl Tokenizable for u128 {
fn from_token(token: Token) -> Result<Self> {
match token {
Token::U128(data) => Ok(data),
other => Err(error!(Other, "expected `u128`, got {:?}", other)),
}
}
fn into_token(self) -> Token {
Token::U128(self)
}
}
impl Tokenizable for RawSlice {
fn from_token(token: Token) -> Result<Self>
where
Self: Sized,
{
match token {
Token::RawSlice(contents) => Ok(Self(contents)),
_ => Err(error!(
Other,
"`RawSlice::from_token` expected a token of the variant `Token::RawSlice`, got: `{token}`"
)),
}
}
fn into_token(self) -> Token {
Token::RawSlice(Vec::from(self))
}
}
impl Tokenizable for Bytes {
fn from_token(token: Token) -> Result<Self>
where
Self: Sized,
{
match token {
Token::Bytes(contents) => Ok(Self(contents)),
_ => Err(error!(
Other,
"`Bytes::from_token` expected a token of the variant `Token::Bytes`, got: `{token}`"
)),
}
}
fn into_token(self) -> Token {
Token::Bytes(Vec::from(self))
}
}
impl Tokenizable for String {
fn from_token(token: Token) -> Result<Self>
where
Self: Sized,
{
match token {
Token::String(string) => Ok(string),
_ => Err(error!(
Other,
"`String::from_token` expected a token of the variant `Token::String`, got: `{token}`"
)),
}
}
fn into_token(self) -> Token {
Token::String(self)
}
}
// Here we implement `Tokenizable` for a given tuple of a given length.
// This is done this way because we can't use `impl<T> Tokenizable for (T,)`.
// So we implement `Tokenizable` for each tuple length, covering
// a reasonable range of tuple lengths.
macro_rules! impl_tokenizable_tuples {
($num: expr, $( $ty: ident : $no: tt, )+) => {
impl<$($ty, )+> Tokenizable for ($($ty,)+) where
$(
$ty: Tokenizable,
)+
{
fn from_token(token: Token) -> Result<Self> {
match token {
Token::Tuple(tokens) => {
let mut it = tokens.into_iter();
let mut next_token = move || {
it.next().ok_or_else(|| {
error!(Other, "ran out of tokens before tuple could be constructed")
})
};
Ok(($(
$ty::from_token(next_token()?)?,
)+))
},
other => Err(error!(Other,
"expected `Tuple`, got `{:?}`",
other
)),
}
}
fn into_token(self) -> Token {
Token::Tuple(vec![
$( self.$no.into_token(), )+
])
}
}
}
}
// And where we actually implement the `Tokenizable` for tuples
// from size 1 to size 16.
impl_tokenizable_tuples!(1, A:0, );
impl_tokenizable_tuples!(2, A:0, B:1, );
impl_tokenizable_tuples!(3, A:0, B:1, C:2, );
impl_tokenizable_tuples!(4, A:0, B:1, C:2, D:3, );
impl_tokenizable_tuples!(5, A:0, B:1, C:2, D:3, E:4, );
impl_tokenizable_tuples!(6, A:0, B:1, C:2, D:3, E:4, F:5, );
impl_tokenizable_tuples!(7, A:0, B:1, C:2, D:3, E:4, F:5, G:6, );
impl_tokenizable_tuples!(8, A:0, B:1, C:2, D:3, E:4, F:5, G:6, H:7, );
impl_tokenizable_tuples!(9, A:0, B:1, C:2, D:3, E:4, F:5, G:6, H:7, I:8, );
impl_tokenizable_tuples!(10, A:0, B:1, C:2, D:3, E:4, F:5, G:6, H:7, I:8, J:9, );
impl_tokenizable_tuples!(11, A:0, B:1, C:2, D:3, E:4, F:5, G:6, H:7, I:8, J:9, K:10, );
impl_tokenizable_tuples!(12, A:0, B:1, C:2, D:3, E:4, F:5, G:6, H:7, I:8, J:9, K:10, L:11, );
impl_tokenizable_tuples!(13, A:0, B:1, C:2, D:3, E:4, F:5, G:6, H:7, I:8, J:9, K:10, L:11, M:12, );
impl_tokenizable_tuples!(14, A:0, B:1, C:2, D:3, E:4, F:5, G:6, H:7, I:8, J:9, K:10, L:11, M:12, N:13, );
impl_tokenizable_tuples!(15, A:0, B:1, C:2, D:3, E:4, F:5, G:6, H:7, I:8, J:9, K:10, L:11, M:12, N:13, O:14, );
impl_tokenizable_tuples!(16, A:0, B:1, C:2, D:3, E:4, F:5, G:6, H:7, I:8, J:9, K:10, L:11, M:12, N:13, O:14, P:15, );
impl Tokenizable for ContractId {
fn from_token(token: Token) -> Result<Self>
where
Self: Sized,
{
if let Token::Struct(tokens) = token {
if let [Token::B256(data)] = tokens.as_slice() {
Ok(ContractId::from(*data))
} else {
Err(error!(
Other,
"`ContractId` expected one `Token::B256`, got `{tokens:?}`"
))
}
} else {
Err(error!(
Other,
"`ContractId` expected `Token::Struct` got `{token:?}`"
))
}
}
fn into_token(self) -> Token {
let underlying_data: &[u8; 32] = &self;
Token::Struct(vec![Bits256(*underlying_data).into_token()])
}
}
impl Tokenizable for Address {
fn from_token(token: Token) -> Result<Self>
where
Self: Sized,
{
if let Token::Struct(tokens) = token {
if let [Token::B256(data)] = tokens.as_slice() {
Ok(Address::from(*data))
} else {
Err(error!(
Other,
"`Address` expected one `Token::B256`, got `{tokens:?}`"
))
}
} else {
Err(error!(
Other,
"`Address` expected `Token::Struct` got `{token:?}`"
))
}
}
fn into_token(self) -> Token {
let underlying_data: &[u8; 32] = &self;
Token::Struct(vec![Bits256(*underlying_data).into_token()])
}
}
impl Tokenizable for AssetId {
fn from_token(token: Token) -> Result<Self>
where
Self: Sized,
{
if let Token::Struct(tokens) = token {
if let [Token::B256(data)] = tokens.as_slice() {
Ok(AssetId::from(*data))
} else {
Err(error!(
Other,
"`AssetId` expected one `Token::B256`, got `{tokens:?}`"
))
}
} else {
Err(error!(
Other,
"`AssetId` expected `Token::Struct` got `{token:?}`"
))
}
}
fn into_token(self) -> Token {
let underlying_data: &[u8; 32] = &self;
Token::Struct(vec![Bits256(*underlying_data).into_token()])
}
}
impl<T> Tokenizable for Option<T>
where
T: Tokenizable + Parameterize,
{
fn from_token(token: Token) -> Result<Self> {
if let Token::Enum(enum_selector) = token {
match *enum_selector {
(0, _, _) => Ok(None),
(1, token, _) => Ok(Option::<T>::Some(T::from_token(token)?)),
(_, _, _) => Err(error!(
Other,
"could not construct `Option` from `enum_selector`. Received: `{:?}`",
enum_selector
)),
}
} else {
Err(error!(
Other,
"could not construct `Option` from token. Received: `{token:?}`"
))
}
}
fn into_token(self) -> Token {
let (dis, tok) = match self {
None => (0, Token::Unit),
Some(value) => (1, value.into_token()),
};
if let ParamType::Enum { enum_variants, .. } = Self::param_type() {
let selector = (dis, tok, enum_variants);
Token::Enum(Box::new(selector))
} else {
panic!("should never happen as `Option::param_type()` returns valid Enum variants");
}
}
}
impl<T, E> Tokenizable for std::result::Result<T, E>
where
T: Tokenizable + Parameterize,
E: Tokenizable + Parameterize,
{
fn from_token(token: Token) -> Result<Self> {
if let Token::Enum(enum_selector) = token {
match *enum_selector {
(0, token, _) => Ok(std::result::Result::<T, E>::Ok(T::from_token(token)?)),
(1, token, _) => Ok(std::result::Result::<T, E>::Err(E::from_token(token)?)),
(_, _, _) => Err(error!(
Other,
"could not construct `Result` from `enum_selector`. Received: `{:?}`",
enum_selector
)),
}
} else {
Err(error!(
Other,
"could not construct `Result` from token. Received: `{token:?}`"
))
}
}
fn into_token(self) -> Token {
let (dis, tok) = match self {
Ok(value) => (0, value.into_token()),
Err(value) => (1, value.into_token()),
};
if let ParamType::Enum { enum_variants, .. } = Self::param_type() {
let selector = (dis, tok, enum_variants);
Token::Enum(Box::new(selector))
} else {
panic!("should never happen as Result::param_type() returns valid Enum variants");
}
}
}
impl<const SIZE: usize, T: Tokenizable> Tokenizable for [T; SIZE] {
fn from_token(token: Token) -> Result<Self>
where
Self: Sized,
{
let gen_error = |reason| error!(Other, "constructing an array of size {SIZE}: {reason}");
match token {
Token::Array(elements) => {
let len = elements.len();
if len != SIZE {
return Err(gen_error(format!(
"`Token::Array` has wrong number of elements: {len}"
)));
}
let detokenized = elements
.into_iter()
.map(Tokenizable::from_token)
.collect::<Result<Vec<T>>>()
.map_err(|err| {
gen_error(format!(", not all elements could be detokenized: {err}"))
})?;
Ok(detokenized.try_into().unwrap_or_else(|_| {
panic!("this should never fail since we're checking the length beforehand")
}))
}
_ => Err(gen_error(format!("expected a `Token::Array`, got {token}"))),
}
}
fn into_token(self) -> Token {
Token::Array(self.map(Tokenizable::into_token).to_vec())
}
}
impl<const LEN: usize> Tokenizable for SizedAsciiString<LEN> {
fn from_token(token: Token) -> Result<Self>
where
Self: Sized,
{
match token {
Token::StringArray(contents) => {
let expected_len = contents.get_encodable_str()?.len();
if expected_len != LEN {
return Err(error!(
Other,
"`SizedAsciiString<{LEN}>::from_token` got a `Token::StringArray` whose expected length({}) is != {LEN}",
expected_len
));
}
Self::new(contents.try_into()?)
}
_ => Err(error!(
Other,
"`SizedAsciiString<{LEN}>::from_token` expected a token of the variant `Token::StringArray`, got: `{token}`"
)),
}
}
fn into_token(self) -> Token {
Token::StringArray(StaticStringToken::new(self.into(), Some(LEN)))
}
}
impl Tokenizable for AsciiString {
fn from_token(token: Token) -> Result<Self>
where
Self: Sized,
{
match token {
Token::StringSlice(contents) => Self::new(contents.try_into()?),
_ => Err(error!(
Other,
"`AsciiString::from_token` expected a token of the variant `Token::StringSlice`, got: `{token}`"
)),
}
}
fn into_token(self) -> Token {
Token::StringSlice(StaticStringToken::new(self.into(), None))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_from_token_b256() -> Result<()> {
let data = [1u8; 32];
let token = Token::B256(data);
let bits256 = Bits256::from_token(token)?;
assert_eq!(bits256.0, data);
Ok(())
}
#[test]
fn test_into_token_b256() {
let bytes = [1u8; 32];
let bits256 = Bits256(bytes);
let token = bits256.into_token();
assert_eq!(token, Token::B256(bytes));
}
#[test]
fn test_from_token_raw_slice() -> Result<()> {
let data = vec![42; 11];
let token = Token::RawSlice(data.clone());
let slice = RawSlice::from_token(token)?;
assert_eq!(slice, data);
Ok(())
}
#[test]
fn test_into_token_raw_slice() {
let data = vec![13; 32];
let raw_slice_token = Token::RawSlice(data.clone());
let token = raw_slice_token.into_token();
assert_eq!(token, Token::RawSlice(data));
}
#[test]
fn sized_ascii_string_is_tokenized_correctly() -> Result<()> {
let sut = SizedAsciiString::<3>::new("abc".to_string())?;
let token = sut.into_token();
match token {
Token::StringArray(string_token) => {
let contents = string_token.get_encodable_str()?;
assert_eq!(contents, "abc");
}
_ => {
panic!("not tokenized correctly! Should have gotten a `Token::String`")
}
}
Ok(())
}
#[test]
fn sized_ascii_string_is_detokenized_correctly() -> Result<()> {
let token = Token::StringArray(StaticStringToken::new("abc".to_string(), Some(3)));
let sized_ascii_string =
SizedAsciiString::<3>::from_token(token).expect("should have succeeded");
assert_eq!(sized_ascii_string, "abc");
Ok(())
}
#[test]
fn test_into_token_std_string() -> Result<()> {
let expected = String::from("hello");
let token = Token::String(expected.clone());
let detokenized = String::from_token(token.into_token())?;
assert_eq!(detokenized, expected);
Ok(())
}
}
| rust | Apache-2.0 | 865e00c295de8b4a0a1ef7ac926c3c8266d5151b | 2026-01-04T15:31:59.450823Z | false |
FuelLabs/fuels-rs | https://github.com/FuelLabs/fuels-rs/blob/865e00c295de8b4a0a1ef7ac926c3c8266d5151b/packages/fuels-core/src/traits/parameterize.rs | packages/fuels-core/src/traits/parameterize.rs | use fuel_types::{Address, AssetId, ContractId};
use crate::types::{
AsciiString, Bits256, Bytes, RawSlice, SizedAsciiString,
param_types::{EnumVariants, ParamType},
};
/// `abigen` requires `Parameterized` to construct nested types. It is also used by `try_from_bytes`
/// to facilitate the instantiation of custom types from bytes.
pub trait Parameterize {
fn param_type() -> ParamType;
}
impl Parameterize for Bits256 {
fn param_type() -> ParamType {
ParamType::B256
}
}
impl Parameterize for RawSlice {
fn param_type() -> ParamType {
ParamType::RawSlice
}
}
impl<const SIZE: usize, T: Parameterize> Parameterize for [T; SIZE] {
fn param_type() -> ParamType {
ParamType::Array(Box::new(T::param_type()), SIZE)
}
}
impl<T: Parameterize> Parameterize for Vec<T> {
fn param_type() -> ParamType {
ParamType::Vector(Box::new(T::param_type()))
}
}
impl Parameterize for Bytes {
fn param_type() -> ParamType {
ParamType::Bytes
}
}
impl Parameterize for String {
fn param_type() -> ParamType {
ParamType::String
}
}
impl Parameterize for Address {
fn param_type() -> ParamType {
ParamType::Struct {
name: "Address".to_string(),
fields: vec![("0".to_string(), ParamType::B256)],
generics: vec![],
}
}
}
impl Parameterize for ContractId {
fn param_type() -> ParamType {
ParamType::Struct {
name: "ContractId".to_string(),
fields: vec![("0".to_string(), ParamType::B256)],
generics: vec![],
}
}
}
impl Parameterize for AssetId {
fn param_type() -> ParamType {
ParamType::Struct {
name: "AssetId".to_string(),
fields: vec![("0".to_string(), ParamType::B256)],
generics: vec![],
}
}
}
impl Parameterize for () {
fn param_type() -> ParamType {
ParamType::Unit
}
}
impl Parameterize for bool {
fn param_type() -> ParamType {
ParamType::Bool
}
}
impl Parameterize for u8 {
fn param_type() -> ParamType {
ParamType::U8
}
}
impl Parameterize for u16 {
fn param_type() -> ParamType {
ParamType::U16
}
}
impl Parameterize for u32 {
fn param_type() -> ParamType {
ParamType::U32
}
}
impl Parameterize for u64 {
fn param_type() -> ParamType {
ParamType::U64
}
}
impl Parameterize for u128 {
fn param_type() -> ParamType {
ParamType::U128
}
}
impl<T> Parameterize for Option<T>
where
T: Parameterize,
{
fn param_type() -> ParamType {
let variant_param_types = vec![
("None".to_string(), ParamType::Unit),
("Some".to_string(), T::param_type()),
];
let enum_variants = EnumVariants::new(variant_param_types)
.expect("should never happen as we provided valid Option param types");
ParamType::Enum {
name: "Option".to_string(),
enum_variants,
generics: vec![T::param_type()],
}
}
}
impl<T, E> Parameterize for Result<T, E>
where
T: Parameterize,
E: Parameterize,
{
fn param_type() -> ParamType {
let variant_param_types = vec![
("Ok".to_string(), T::param_type()),
("Err".to_string(), E::param_type()),
];
let enum_variants = EnumVariants::new(variant_param_types)
.expect("should never happen as we provided valid Result param types");
ParamType::Enum {
name: "Result".to_string(),
enum_variants,
generics: vec![T::param_type(), E::param_type()],
}
}
}
impl<const LEN: usize> Parameterize for SizedAsciiString<LEN> {
fn param_type() -> ParamType {
ParamType::StringArray(LEN)
}
}
impl Parameterize for AsciiString {
fn param_type() -> ParamType {
ParamType::StringSlice
}
}
// Here we implement `Parameterize` for a given tuple of a given length.
// This is done this way because we can't use `impl<T> Parameterize for (T,)`.
// So we implement `Parameterize` for each tuple length, covering
// a reasonable range of tuple lengths.
macro_rules! impl_parameterize_tuples {
($num: expr, $( $ty: ident : $no: tt, )+) => {
impl<$($ty, )+> Parameterize for ($($ty,)+) where
$(
$ty: Parameterize,
)+
{
fn param_type() -> ParamType {
ParamType::Tuple(vec![
$( $ty::param_type(), )+
])
}
}
}
}
// And where we actually implement the `Parameterize` for tuples
// from size 1 to size 16.
impl_parameterize_tuples!(1, A:0, );
impl_parameterize_tuples!(2, A:0, B:1, );
impl_parameterize_tuples!(3, A:0, B:1, C:2, );
impl_parameterize_tuples!(4, A:0, B:1, C:2, D:3, );
impl_parameterize_tuples!(5, A:0, B:1, C:2, D:3, E:4, );
impl_parameterize_tuples!(6, A:0, B:1, C:2, D:3, E:4, F:5, );
impl_parameterize_tuples!(7, A:0, B:1, C:2, D:3, E:4, F:5, G:6, );
impl_parameterize_tuples!(8, A:0, B:1, C:2, D:3, E:4, F:5, G:6, H:7, );
impl_parameterize_tuples!(9, A:0, B:1, C:2, D:3, E:4, F:5, G:6, H:7, I:8, );
impl_parameterize_tuples!(10, A:0, B:1, C:2, D:3, E:4, F:5, G:6, H:7, I:8, J:9, );
impl_parameterize_tuples!(11, A:0, B:1, C:2, D:3, E:4, F:5, G:6, H:7, I:8, J:9, K:10, );
impl_parameterize_tuples!(12, A:0, B:1, C:2, D:3, E:4, F:5, G:6, H:7, I:8, J:9, K:10, L:11, );
impl_parameterize_tuples!(13, A:0, B:1, C:2, D:3, E:4, F:5, G:6, H:7, I:8, J:9, K:10, L:11, M:12, );
impl_parameterize_tuples!(14, A:0, B:1, C:2, D:3, E:4, F:5, G:6, H:7, I:8, J:9, K:10, L:11, M:12, N:13, );
impl_parameterize_tuples!(15, A:0, B:1, C:2, D:3, E:4, F:5, G:6, H:7, I:8, J:9, K:10, L:11, M:12, N:13, O:14, );
impl_parameterize_tuples!(16, A:0, B:1, C:2, D:3, E:4, F:5, G:6, H:7, I:8, J:9, K:10, L:11, M:12, N:13, O:14, P:15, );
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn sized_ascii_string_is_parameterized_correctly() {
let param_type = SizedAsciiString::<3>::param_type();
assert!(matches!(param_type, ParamType::StringArray(3)));
}
#[test]
fn test_param_type_b256() {
assert_eq!(Bits256::param_type(), ParamType::B256);
}
#[test]
fn test_param_type_raw_slice() {
assert_eq!(RawSlice::param_type(), ParamType::RawSlice);
}
}
| rust | Apache-2.0 | 865e00c295de8b4a0a1ef7ac926c3c8266d5151b | 2026-01-04T15:31:59.450823Z | false |
FuelLabs/fuels-rs | https://github.com/FuelLabs/fuels-rs/blob/865e00c295de8b4a0a1ef7ac926c3c8266d5151b/packages/fuels-accounts/src/lib.rs | packages/fuels-accounts/src/lib.rs | #[cfg(feature = "std")]
mod account;
#[cfg(feature = "std")]
mod accounts_utils;
#[cfg(all(feature = "std", feature = "keystore"))]
pub mod keystore;
#[cfg(feature = "std")]
pub mod provider;
#[cfg(feature = "std")]
pub mod wallet;
#[cfg(feature = "std")]
pub use account::*;
#[cfg(feature = "coin-cache")]
mod coin_cache;
pub mod predicate;
pub mod signers;
#[cfg(test)]
mod test {
#[test]
fn sdl_is_the_same_as_from_fuel() {
let file_sdl = include_str!("./schema/schema.sdl");
let core_sdl = String::from_utf8(fuel_core_client::SCHEMA_SDL.to_vec()).unwrap();
assert_eq!(file_sdl, &core_sdl);
}
}
| rust | Apache-2.0 | 865e00c295de8b4a0a1ef7ac926c3c8266d5151b | 2026-01-04T15:31:59.450823Z | false |
FuelLabs/fuels-rs | https://github.com/FuelLabs/fuels-rs/blob/865e00c295de8b4a0a1ef7ac926c3c8266d5151b/packages/fuels-accounts/src/signers.rs | packages/fuels-accounts/src/signers.rs | pub mod derivation {
pub const BIP44_PURPOSE: &str = "44'";
pub const COIN_TYPE: &str = "1179993420'";
pub const DEFAULT_DERIVATION_PATH: &str = "m/44'/1179993420'/0'/0/0";
}
#[cfg(any(feature = "signer-aws-kms", feature = "signer-google-kms"))]
pub mod kms;
pub mod fake;
pub mod private_key;
| rust | Apache-2.0 | 865e00c295de8b4a0a1ef7ac926c3c8266d5151b | 2026-01-04T15:31:59.450823Z | false |
FuelLabs/fuels-rs | https://github.com/FuelLabs/fuels-rs/blob/865e00c295de8b4a0a1ef7ac926c3c8266d5151b/packages/fuels-accounts/src/coin_cache.rs | packages/fuels-accounts/src/coin_cache.rs | use std::{
collections::{HashMap, HashSet},
hash::{Hash, Hasher},
};
use fuel_types::AssetId;
use fuels_core::types::{Address, coin_type_id::CoinTypeId};
use tokio::time::{Duration, Instant};
type CoinCacheKey = (Address, AssetId);
#[derive(Debug)]
pub(crate) struct CoinsCache {
ttl: Duration,
items: HashMap<CoinCacheKey, HashSet<CoinCacheItem>>,
}
impl Default for CoinsCache {
fn default() -> Self {
Self::new(Duration::from_secs(30))
}
}
impl CoinsCache {
pub fn new(ttl: Duration) -> Self {
Self {
ttl,
items: HashMap::default(),
}
}
pub fn insert_multiple(
&mut self,
coin_ids: impl IntoIterator<Item = (CoinCacheKey, Vec<CoinTypeId>)>,
) {
for (key, ids) in coin_ids {
let new_items = ids.into_iter().map(CoinCacheItem::new);
let items = self.items.entry(key).or_default();
items.extend(new_items);
}
}
pub fn get_active(&mut self, key: &CoinCacheKey) -> HashSet<CoinTypeId> {
self.remove_expired_entries(key);
self.items
.get(key)
.cloned()
.unwrap_or_default()
.into_iter()
.map(|item| item.id)
.collect()
}
pub fn remove_items(
&mut self,
inputs: impl IntoIterator<Item = (CoinCacheKey, Vec<CoinTypeId>)>,
) {
for (key, ids) in inputs {
for id in ids {
self.remove(&key, id);
}
}
}
fn remove(&mut self, key: &CoinCacheKey, id: CoinTypeId) {
if let Some(ids) = self.items.get_mut(key) {
let item = CoinCacheItem::new(id);
ids.remove(&item);
}
}
fn remove_expired_entries(&mut self, key: &CoinCacheKey) {
if let Some(entry) = self.items.get_mut(key) {
entry.retain(|item| item.is_valid(self.ttl));
}
}
}
#[derive(Eq, Debug, Clone)]
struct CoinCacheItem {
created_at: Instant,
pub id: CoinTypeId,
}
impl PartialEq for CoinCacheItem {
fn eq(&self, other: &Self) -> bool {
self.id.eq(&other.id)
}
}
impl Hash for CoinCacheItem {
fn hash<H: Hasher>(&self, state: &mut H) {
self.id.hash(state);
}
}
impl CoinCacheItem {
pub fn new(id: CoinTypeId) -> Self {
Self {
created_at: Instant::now(),
id,
}
}
pub fn is_valid(&self, ttl: Duration) -> bool {
self.created_at + ttl > Instant::now()
}
}
#[cfg(test)]
mod tests {
use fuel_tx::UtxoId;
use fuel_types::{Bytes32, Nonce};
use super::*;
fn get_items() -> (CoinTypeId, CoinTypeId) {
let utxo_id = UtxoId::new(Bytes32::from([1u8; 32]), 0);
let nonce = Nonce::new([2u8; 32]);
(CoinTypeId::UtxoId(utxo_id), CoinTypeId::Nonce(nonce))
}
#[test]
fn test_insert_and_get_active() {
let mut cache = CoinsCache::new(Duration::from_secs(60));
let key: CoinCacheKey = Default::default();
let (item1, item2) = get_items();
let items = HashMap::from([(key, vec![item1.clone(), item2.clone()])]);
cache.insert_multiple(items);
let active_coins = cache.get_active(&key);
assert_eq!(active_coins.len(), 2);
assert!(active_coins.contains(&item1));
assert!(active_coins.contains(&item2));
}
#[tokio::test]
async fn test_insert_and_expire_items() {
let mut cache = CoinsCache::new(Duration::from_secs(10));
let key = CoinCacheKey::default();
let (item1, _) = get_items();
let items = HashMap::from([(key, vec![item1.clone()])]);
cache.insert_multiple(items);
// Advance time by more than the cache's TTL
tokio::time::pause();
tokio::time::advance(Duration::from_secs(12)).await;
let (_, item2) = get_items();
let items = HashMap::from([(key, vec![item2.clone()])]);
cache.insert_multiple(items);
let active_coins = cache.get_active(&key);
assert_eq!(active_coins.len(), 1);
assert!(!active_coins.contains(&item1));
assert!(active_coins.contains(&item2));
}
#[test]
fn test_get_active_no_items() {
let mut cache = CoinsCache::new(Duration::from_secs(60));
let key = Default::default();
let active_coins = cache.get_active(&key);
assert!(active_coins.is_empty());
}
#[test]
fn test_remove_items() {
let mut cache = CoinsCache::new(Duration::from_secs(60));
let key: CoinCacheKey = Default::default();
let (item1, item2) = get_items();
let items_to_insert = [(key, vec![item1.clone(), item2.clone()])];
cache.insert_multiple(items_to_insert.iter().cloned());
let items_to_remove = [(key, vec![item1.clone()])];
cache.remove_items(items_to_remove.iter().cloned());
let active_coins = cache.get_active(&key);
assert_eq!(active_coins.len(), 1);
assert!(!active_coins.contains(&item1));
assert!(active_coins.contains(&item2));
}
}
| rust | Apache-2.0 | 865e00c295de8b4a0a1ef7ac926c3c8266d5151b | 2026-01-04T15:31:59.450823Z | false |
FuelLabs/fuels-rs | https://github.com/FuelLabs/fuels-rs/blob/865e00c295de8b4a0a1ef7ac926c3c8266d5151b/packages/fuels-accounts/src/predicate.rs | packages/fuels-accounts/src/predicate.rs | use std::{fmt::Debug, fs};
#[cfg(feature = "std")]
use fuels_core::types::{AssetId, coin_type_id::CoinTypeId, input::Input};
use fuels_core::{
Configurables, error,
types::{Address, errors::Result},
};
#[cfg(feature = "std")]
use crate::accounts_utils::try_provider_error;
#[cfg(feature = "std")]
use crate::{Account, ViewOnlyAccount, provider::Provider};
#[derive(Debug, Clone)]
pub struct Predicate {
address: Address,
code: Vec<u8>,
data: Vec<u8>,
#[cfg(feature = "std")]
provider: Option<Provider>,
}
impl Predicate {
pub fn address(&self) -> Address {
self.address
}
pub fn code(&self) -> &[u8] {
&self.code
}
pub fn data(&self) -> &[u8] {
&self.data
}
pub fn calculate_address(code: &[u8]) -> Address {
fuel_tx::Input::predicate_owner(code)
}
pub fn load_from(file_path: &str) -> Result<Self> {
let code = fs::read(file_path).map_err(|e| {
error!(
IO,
"could not read predicate binary {file_path:?}. Reason: {e}"
)
})?;
Ok(Self::from_code(code))
}
pub fn from_code(code: Vec<u8>) -> Self {
Self {
address: Self::calculate_address(&code),
code,
data: Default::default(),
#[cfg(feature = "std")]
provider: None,
}
}
pub fn with_data(mut self, data: Vec<u8>) -> Self {
self.data = data;
self
}
pub fn with_code(self, code: Vec<u8>) -> Self {
let address = Self::calculate_address(&code);
Self {
code,
address,
..self
}
}
pub fn with_configurables(mut self, configurables: impl Into<Configurables>) -> Self {
let configurables: Configurables = configurables.into();
configurables.update_constants_in(&mut self.code);
let address = Self::calculate_address(&self.code);
self.address = address;
self
}
}
#[cfg(feature = "std")]
impl Predicate {
pub fn provider(&self) -> Option<&Provider> {
self.provider.as_ref()
}
pub fn set_provider(&mut self, provider: Provider) {
self.provider = Some(provider);
}
pub fn with_provider(self, provider: Provider) -> Self {
Self {
provider: Some(provider),
..self
}
}
}
#[cfg(feature = "std")]
#[cfg_attr(not(target_arch = "wasm32"), async_trait::async_trait)]
impl ViewOnlyAccount for Predicate {
fn address(&self) -> Address {
self.address()
}
fn try_provider(&self) -> Result<&Provider> {
self.provider.as_ref().ok_or_else(try_provider_error)
}
async fn get_asset_inputs_for_amount(
&self,
asset_id: AssetId,
amount: u128,
excluded_coins: Option<Vec<CoinTypeId>>,
) -> Result<Vec<Input>> {
Ok(self
.get_spendable_resources(asset_id, amount, excluded_coins)
.await?
.into_iter()
.map(|resource| {
Input::resource_predicate(resource, self.code.clone(), self.data.clone())
})
.collect::<Vec<Input>>())
}
}
#[cfg(feature = "std")]
impl Account for Predicate {}
| rust | Apache-2.0 | 865e00c295de8b4a0a1ef7ac926c3c8266d5151b | 2026-01-04T15:31:59.450823Z | false |
FuelLabs/fuels-rs | https://github.com/FuelLabs/fuels-rs/blob/865e00c295de8b4a0a1ef7ac926c3c8266d5151b/packages/fuels-accounts/src/keystore.rs | packages/fuels-accounts/src/keystore.rs | use std::path::{Path, PathBuf};
use fuel_crypto::SecretKey;
use fuels_core::{error, types::errors::Result};
use rand::{CryptoRng, Rng};
use zeroize::{Zeroize, ZeroizeOnDrop};
#[derive(Debug, Clone, Zeroize, ZeroizeOnDrop)]
pub struct KeySaved {
key: SecretKey,
#[zeroize(skip)]
uuid: String,
}
impl KeySaved {
pub fn key(&self) -> &SecretKey {
&self.key
}
pub fn uuid(&self) -> &str {
&self.uuid
}
}
/// A Keystore encapsulates operations for key management such as creation, loading,
/// and saving of keys into a specified directory.
pub struct Keystore {
dir: PathBuf,
}
impl Keystore {
/// Creates a new Keystore instance with the provided directory.
pub fn new<P: AsRef<Path>>(dir: P) -> Self {
Self {
dir: dir.as_ref().to_path_buf(),
}
}
/// Loads and decrypts a key from the keystore using the given UUID and password.
pub fn load_key<S>(&self, uuid: &str, password: S) -> Result<SecretKey>
where
S: AsRef<[u8]>,
{
let key_path = self.dir.join(uuid);
let secret =
eth_keystore::decrypt_key(key_path, password).map_err(|e| error!(Other, "{e}"))?;
let secret_key = SecretKey::try_from(secret.as_slice())
.expect("Decrypted key should have a correct size");
Ok(secret_key)
}
/// Encrypts the provided key with the given password and saves it to the keystore.
/// Returns the generated UUID for the stored key.
pub fn save_key<R, S>(&self, key: SecretKey, password: S, mut rng: R) -> Result<String>
where
R: Rng + CryptoRng,
S: AsRef<[u8]>,
{
// Note: `*key` is used if SecretKey implements Deref to an inner type.
eth_keystore::encrypt_key(&self.dir, &mut rng, *key, password, None)
.map_err(|e| error!(Other, "{e}"))
}
}
#[cfg(test)]
mod tests {
use rand::thread_rng;
use tempfile::tempdir;
use super::*;
use crate::signers::private_key::PrivateKeySigner;
#[tokio::test]
async fn wallet_from_mnemonic_phrase() -> Result<()> {
let phrase =
"oblige salon price punch saddle immune slogan rare snap desert retire surprise";
// Create first key from mnemonic phrase.
let key = SecretKey::new_from_mnemonic_phrase_with_path(phrase, "m/44'/60'/0'/0/0")?;
let signer = PrivateKeySigner::new(key);
let expected_address = "df9d0e6c6c5f5da6e82e5e1a77974af6642bdb450a10c43f0c6910a212600185";
assert_eq!(signer.address().to_string(), expected_address);
// Create a second key from the same phrase.
let key = SecretKey::new_from_mnemonic_phrase_with_path(phrase, "m/44'/60'/1'/0/0")?;
let signer2 = PrivateKeySigner::new(key);
let expected_second_address =
"261191b0164a24fd0fd51566ec5e5b0b9ba8fb2d42dc9cf7dbbd6f23d2742759";
assert_eq!(signer2.address().to_string(), expected_second_address);
Ok(())
}
#[tokio::test]
async fn encrypt_and_store_keys_from_mnemonic() -> Result<()> {
let dir = tempdir()?;
let keystore = Keystore::new(dir.path());
let phrase =
"oblige salon price punch saddle immune slogan rare snap desert retire surprise";
// Create a key from the mnemonic phrase.
let key = SecretKey::new_from_mnemonic_phrase_with_path(phrase, "m/44'/60'/0'/0/0")?;
let uuid = keystore.save_key(key, "password", thread_rng())?;
let recovered_key = keystore.load_key(&uuid, "password")?;
assert_eq!(key, recovered_key);
// Remove the keystore file.
let key_path = keystore.dir.join(&uuid);
assert!(std::fs::remove_file(key_path).is_ok());
Ok(())
}
}
| rust | Apache-2.0 | 865e00c295de8b4a0a1ef7ac926c3c8266d5151b | 2026-01-04T15:31:59.450823Z | false |
FuelLabs/fuels-rs | https://github.com/FuelLabs/fuels-rs/blob/865e00c295de8b4a0a1ef7ac926c3c8266d5151b/packages/fuels-accounts/src/wallet.rs | packages/fuels-accounts/src/wallet.rs | use crate::{provider::Provider, signers::private_key::PrivateKeySigner};
#[derive(Debug, Clone)]
pub struct Wallet<S = Unlocked<PrivateKeySigner>> {
state: S,
provider: Provider,
}
impl<S> Wallet<S> {
pub fn set_provider(&mut self, provider: Provider) {
self.provider = provider;
}
pub fn provider(&self) -> &Provider {
&self.provider
}
}
mod unlocked {
use async_trait::async_trait;
use fuels_core::{
traits::Signer,
types::{
Address, AssetId, coin_type_id::CoinTypeId, errors::Result, input::Input,
transaction_builders::TransactionBuilder,
},
};
use rand::{CryptoRng, RngCore};
use super::{Locked, Wallet};
use crate::{
Account, ViewOnlyAccount, provider::Provider, signers::private_key::PrivateKeySigner,
};
#[derive(Debug, Clone)]
pub struct Unlocked<S> {
signer: S,
}
impl<S> Unlocked<S> {
fn new(signer: S) -> Self {
Self { signer }
}
}
impl<S> Wallet<Unlocked<S>> {
pub fn new(signer: S, provider: Provider) -> Self {
Wallet {
state: Unlocked::new(signer),
provider,
}
}
pub fn signer(&self) -> &S {
&self.state.signer
}
}
impl Wallet<Unlocked<PrivateKeySigner>> {
pub fn random(rng: &mut (impl CryptoRng + RngCore), provider: Provider) -> Self {
Self::new(PrivateKeySigner::random(rng), provider)
}
}
impl<S> Wallet<Unlocked<S>>
where
S: Signer,
{
pub fn lock(&self) -> Wallet<Locked> {
Wallet::new_locked(self.state.signer.address(), self.provider.clone())
}
}
#[async_trait]
impl<S> ViewOnlyAccount for Wallet<Unlocked<S>>
where
S: Signer + Clone + Send + Sync + std::fmt::Debug + 'static,
{
fn address(&self) -> Address {
self.state.signer.address()
}
fn try_provider(&self) -> Result<&Provider> {
Ok(&self.provider)
}
async fn get_asset_inputs_for_amount(
&self,
asset_id: AssetId,
amount: u128,
excluded_coins: Option<Vec<CoinTypeId>>,
) -> Result<Vec<Input>> {
Ok(self
.get_spendable_resources(asset_id, amount, excluded_coins)
.await?
.into_iter()
.map(Input::resource_signed)
.collect::<Vec<Input>>())
}
}
#[async_trait]
impl<S> Account for Wallet<Unlocked<S>>
where
S: Signer + Clone + Send + Sync + std::fmt::Debug + 'static,
{
fn add_witnesses<Tb: TransactionBuilder>(&self, tb: &mut Tb) -> Result<()> {
tb.add_signer(self.state.signer.clone())?;
Ok(())
}
}
}
pub use unlocked::*;
mod locked {
use async_trait::async_trait;
use fuels_core::types::{
Address, AssetId, coin_type_id::CoinTypeId, errors::Result, input::Input,
};
use super::Wallet;
use crate::{ViewOnlyAccount, provider::Provider};
#[derive(Debug, Clone)]
pub struct Locked {
address: Address,
}
impl Locked {
fn new(address: Address) -> Self {
Self { address }
}
}
impl Wallet<Locked> {
pub fn new_locked(addr: Address, provider: Provider) -> Self {
Self {
state: Locked::new(addr),
provider,
}
}
}
#[async_trait]
impl ViewOnlyAccount for Wallet<Locked> {
fn address(&self) -> Address {
self.state.address
}
fn try_provider(&self) -> Result<&Provider> {
Ok(&self.provider)
}
async fn get_asset_inputs_for_amount(
&self,
asset_id: AssetId,
amount: u128,
excluded_coins: Option<Vec<CoinTypeId>>,
) -> Result<Vec<Input>> {
Ok(self
.get_spendable_resources(asset_id, amount, excluded_coins)
.await?
.into_iter()
.map(Input::resource_signed)
.collect::<Vec<Input>>())
}
}
}
pub use locked::*;
| rust | Apache-2.0 | 865e00c295de8b4a0a1ef7ac926c3c8266d5151b | 2026-01-04T15:31:59.450823Z | false |
FuelLabs/fuels-rs | https://github.com/FuelLabs/fuels-rs/blob/865e00c295de8b4a0a1ef7ac926c3c8266d5151b/packages/fuels-accounts/src/accounts_utils.rs | packages/fuels-accounts/src/accounts_utils.rs | use fuel_tx::{AssetId, Output, Receipt, UtxoId};
use fuel_types::Nonce;
use fuels_core::types::{
Address,
coin::Coin,
coin_type::CoinType,
coin_type_id::CoinTypeId,
errors::{Error, Result, error},
input::Input,
transaction_builders::TransactionBuilder,
};
use itertools::{Either, Itertools};
use crate::provider::Provider;
pub fn extract_message_nonce(receipts: &[Receipt]) -> Option<Nonce> {
receipts.iter().find_map(|m| m.nonce()).copied()
}
pub async fn calculate_missing_base_amount(
tb: &impl TransactionBuilder,
available_base_amount: u128,
reserved_base_amount: u128,
provider: &Provider,
) -> Result<u128> {
let max_fee: u128 = tb.estimate_max_fee(provider).await?.into();
let total_used = max_fee + reserved_base_amount;
let missing_amount = if total_used > available_base_amount {
total_used - available_base_amount
} else if !is_consuming_utxos(tb) {
// A tx needs to have at least 1 spendable input
// Enforce a minimum required amount on the base asset if no other inputs are present
1
} else {
0
};
Ok(missing_amount)
}
pub fn available_base_assets_and_amount(
tb: &impl TransactionBuilder,
base_asset_id: &AssetId,
) -> (Vec<CoinTypeId>, u128) {
let mut sum = 0u128;
let iter =
tb.inputs()
.iter()
.filter_map(|input| match input {
Input::ResourceSigned { resource, .. }
| Input::ResourcePredicate { resource, .. } => match resource {
CoinType::Coin(Coin {
amount, asset_id, ..
}) if asset_id == base_asset_id => {
sum += u128::from(*amount);
resource.id()
}
CoinType::Message(message) => {
if message.data.is_empty() {
sum += u128::from(message.amount);
resource.id()
} else {
None
}
}
_ => None,
},
_ => None,
})
.collect_vec();
(iter, sum)
}
pub fn split_into_utxo_ids_and_nonces(
excluded_coins: Option<Vec<CoinTypeId>>,
) -> (Vec<UtxoId>, Vec<Nonce>) {
excluded_coins
.map(|excluded_coins| {
excluded_coins
.iter()
.partition_map(|coin_id| match coin_id {
CoinTypeId::UtxoId(utxo_id) => Either::Left(*utxo_id),
CoinTypeId::Nonce(nonce) => Either::Right(*nonce),
})
})
.unwrap_or_default()
}
fn is_consuming_utxos(tb: &impl TransactionBuilder) -> bool {
tb.inputs()
.iter()
.any(|input| !matches!(input, Input::Contract { .. }))
}
pub fn add_base_change_if_needed(
tb: &mut impl TransactionBuilder,
address: Address,
base_asset_id: AssetId,
) {
let is_base_change_present = tb.outputs().iter().any(|output| {
matches!(output , Output::Change { asset_id , .. }
if *asset_id == base_asset_id)
});
if !is_base_change_present {
tb.outputs_mut()
.push(Output::change(address, 0, base_asset_id));
}
}
pub(crate) fn try_provider_error() -> Error {
error!(
Other,
"no provider available. Make sure to use `set_provider`"
)
}
| rust | Apache-2.0 | 865e00c295de8b4a0a1ef7ac926c3c8266d5151b | 2026-01-04T15:31:59.450823Z | false |
FuelLabs/fuels-rs | https://github.com/FuelLabs/fuels-rs/blob/865e00c295de8b4a0a1ef7ac926c3c8266d5151b/packages/fuels-accounts/src/provider.rs | packages/fuels-accounts/src/provider.rs | #[cfg(feature = "coin-cache")]
use std::sync::Arc;
use std::{collections::HashMap, fmt::Debug, net::SocketAddr};
mod cache;
mod retry_util;
mod retryable_client;
mod supported_fuel_core_version;
mod supported_versions;
pub use cache::TtlConfig;
use cache::{CachedClient, SystemClock};
use chrono::{DateTime, Utc};
use fuel_core_client::client::{
FuelClient,
pagination::{PageDirection, PaginatedResult, PaginationRequest},
types::{
balance::Balance,
contract::ContractBalance,
gas_price::{EstimateGasPrice, LatestGasPrice},
},
};
use fuel_core_types::services::executor::TransactionExecutionResult;
use fuel_tx::{
AssetId, ConsensusParameters, Receipt, Transaction as FuelTransaction, TxId, UtxoId,
};
#[cfg(feature = "coin-cache")]
use fuels_core::types::coin_type_id::CoinTypeId;
use fuels_core::{
constants::{DEFAULT_GAS_ESTIMATION_BLOCK_HORIZON, DEFAULT_GAS_ESTIMATION_TOLERANCE},
types::{
Address, BlockHeight, Bytes32, ContractId, DryRun, DryRunner, Nonce,
block::{Block, Header},
chain_info::ChainInfo,
coin::Coin,
coin_type::CoinType,
errors::Result,
message::Message,
message_proof::MessageProof,
node_info::NodeInfo,
transaction::{Transaction, Transactions},
transaction_builders::{Blob, BlobId},
transaction_response::TransactionResponse,
tx_status::TxStatus,
},
};
use futures::StreamExt;
pub use retry_util::{Backoff, RetryConfig};
pub use supported_fuel_core_version::SUPPORTED_FUEL_CORE_VERSION;
use tai64::Tai64;
#[cfg(feature = "coin-cache")]
use tokio::sync::Mutex;
#[cfg(feature = "coin-cache")]
use crate::coin_cache::CoinsCache;
use crate::provider::{cache::CacheableRpcs, retryable_client::RetryableClient};
const NUM_RESULTS_PER_REQUEST: i32 = 100;
#[derive(Debug, Clone, PartialEq)]
// ANCHOR: transaction_cost
pub struct TransactionCost {
pub gas_price: u64,
pub metered_bytes_size: u64,
pub total_fee: u64,
pub script_gas: u64,
pub total_gas: u64,
}
// ANCHOR_END: transaction_cost
pub(crate) struct ResourceQueries {
utxos: Vec<UtxoId>,
messages: Vec<Nonce>,
asset_id: Option<AssetId>,
amount: u128,
}
impl ResourceQueries {
pub fn exclusion_query(&self) -> Option<(Vec<UtxoId>, Vec<Nonce>)> {
if self.utxos.is_empty() && self.messages.is_empty() {
return None;
}
Some((self.utxos.clone(), self.messages.clone()))
}
pub fn spend_query(&self, base_asset_id: AssetId) -> Vec<(AssetId, u128, Option<u16>)> {
vec![(self.asset_id.unwrap_or(base_asset_id), self.amount, None)]
}
}
#[derive(Default)]
// ANCHOR: resource_filter
pub struct ResourceFilter {
pub from: Address,
pub asset_id: Option<AssetId>,
pub amount: u128,
pub excluded_utxos: Vec<UtxoId>,
pub excluded_message_nonces: Vec<Nonce>,
}
// ANCHOR_END: resource_filter
impl ResourceFilter {
pub fn owner(&self) -> Address {
self.from
}
pub(crate) fn resource_queries(&self) -> ResourceQueries {
ResourceQueries {
utxos: self.excluded_utxos.clone(),
messages: self.excluded_message_nonces.clone(),
asset_id: self.asset_id,
amount: self.amount,
}
}
}
/// Encapsulates common client operations in the SDK.
/// Note that you may also use `client`, which is an instance
/// of `FuelClient`, directly, which provides a broader API.
#[derive(Debug, Clone)]
pub struct Provider {
cached_client: CachedClient<RetryableClient>,
#[cfg(feature = "coin-cache")]
coins_cache: Arc<Mutex<CoinsCache>>,
}
impl Provider {
pub async fn from(addr: impl Into<SocketAddr>) -> Result<Self> {
let addr = addr.into();
Self::connect(format!("http://{addr}")).await
}
/// Returns the underlying uncached client.
pub fn client(&self) -> &FuelClient {
self.cached_client.inner().client()
}
pub fn set_cache_ttl(&mut self, ttl: TtlConfig) {
self.cached_client.set_ttl(ttl);
}
pub async fn clear_cache(&self) {
self.cached_client.clear().await;
}
pub async fn healthy(&self) -> Result<bool> {
Ok(self.uncached_client().health().await?)
}
/// Connects to an existing node at the given address.
pub async fn connect(url: impl AsRef<str>) -> Result<Provider> {
let client = CachedClient::new(
RetryableClient::connect(&url, Default::default()).await?,
TtlConfig::default(),
SystemClock,
);
Ok(Self {
cached_client: client,
#[cfg(feature = "coin-cache")]
coins_cache: Default::default(),
})
}
pub fn url(&self) -> &str {
self.uncached_client().url()
}
pub async fn blob(&self, blob_id: BlobId) -> Result<Option<Blob>> {
Ok(self
.uncached_client()
.blob(blob_id.into())
.await?
.map(|blob| Blob::new(blob.bytecode)))
}
pub async fn blob_exists(&self, blob_id: BlobId) -> Result<bool> {
Ok(self.uncached_client().blob_exists(blob_id.into()).await?)
}
/// Sends a transaction to the underlying Provider's client.
pub async fn send_transaction_and_await_commit<T: Transaction>(
&self,
tx: T,
) -> Result<TxStatus> {
#[cfg(feature = "coin-cache")]
let base_asset_id = *self.consensus_parameters().await?.base_asset_id();
#[cfg(feature = "coin-cache")]
self.check_inputs_already_in_cache(&tx.used_coins(&base_asset_id))
.await?;
let tx = self.prepare_transaction_for_sending(tx).await?;
let tx_status = self
.uncached_client()
.submit_and_await_commit(&tx.clone().into())
.await?
.into();
#[cfg(feature = "coin-cache")]
if matches!(
tx_status,
TxStatus::SqueezedOut { .. } | TxStatus::Failure { .. }
) {
self.coins_cache
.lock()
.await
.remove_items(tx.used_coins(&base_asset_id))
}
Ok(tx_status)
}
/// Similar to `send_transaction_and_await_commit`,
/// but collect all the status received until a final one and return them.
pub async fn send_transaction_and_await_status<T: Transaction>(
&self,
tx: T,
include_preconfirmation: bool,
) -> Result<Vec<Result<TxStatus>>> {
#[cfg(feature = "coin-cache")]
let base_asset_id = *self.consensus_parameters().await?.base_asset_id();
#[cfg(feature = "coin-cache")]
let used_base_coins = tx.used_coins(&base_asset_id);
#[cfg(feature = "coin-cache")]
self.check_inputs_already_in_cache(&used_base_coins).await?;
let tx = self.prepare_transaction_for_sending(tx).await?.into();
let mut stream = self
.uncached_client()
.submit_and_await_status(&tx, include_preconfirmation)
.await?;
let mut statuses = Vec::new();
// Process stream items until we get a final status
while let Some(status) = stream.next().await {
let tx_status = status.map(TxStatus::from).map_err(Into::into);
let is_final = tx_status.as_ref().ok().is_some_and(|s| s.is_final());
statuses.push(tx_status);
if is_final {
break;
}
}
// Handle cache updates for failures
#[cfg(feature = "coin-cache")]
if statuses.iter().any(|status| {
matches!(
&status,
Ok(TxStatus::SqueezedOut { .. }) | Ok(TxStatus::Failure { .. }),
)
}) {
self.coins_cache.lock().await.remove_items(used_base_coins);
}
Ok(statuses)
}
async fn prepare_transaction_for_sending<T: Transaction>(&self, mut tx: T) -> Result<T> {
let consensus_parameters = self.consensus_parameters().await?;
tx.precompute(&consensus_parameters.chain_id())?;
let chain_info = self.chain_info().await?;
let Header {
height: latest_block_height,
state_transition_bytecode_version: latest_chain_executor_version,
..
} = chain_info.latest_block.header;
if tx.is_using_predicates() {
tx.estimate_predicates(self, Some(latest_chain_executor_version))
.await?;
tx.clone()
.validate_predicates(&consensus_parameters, latest_block_height)?;
}
Ok(tx)
}
pub async fn send_transaction<T: Transaction>(&self, tx: T) -> Result<TxId> {
let tx = self.prepare_transaction_for_sending(tx).await?;
self.submit(tx).await
}
pub async fn await_transaction_commit<T: Transaction>(&self, id: TxId) -> Result<TxStatus> {
Ok(self
.uncached_client()
.await_transaction_commit(&id)
.await?
.into())
}
#[cfg(not(feature = "coin-cache"))]
async fn submit<T: Transaction>(&self, tx: T) -> Result<TxId> {
Ok(self.uncached_client().submit(&tx.into()).await?)
}
#[cfg(feature = "coin-cache")]
async fn find_in_cache<'a>(
&self,
coin_ids: impl IntoIterator<Item = (&'a (Address, AssetId), &'a Vec<CoinTypeId>)>,
) -> Option<((Address, AssetId), CoinTypeId)> {
let mut locked_cache = self.coins_cache.lock().await;
for (key, ids) in coin_ids {
let items = locked_cache.get_active(key);
if items.is_empty() {
continue;
}
for id in ids {
if items.contains(id) {
return Some((*key, id.clone()));
}
}
}
None
}
#[cfg(feature = "coin-cache")]
async fn check_inputs_already_in_cache<'a>(
&self,
coin_ids: impl IntoIterator<Item = (&'a (Address, AssetId), &'a Vec<CoinTypeId>)>,
) -> Result<()> {
use fuels_core::types::errors::{Error, transaction};
if let Some(((addr, asset_id), coin_type_id)) = self.find_in_cache(coin_ids).await {
let msg = match coin_type_id {
CoinTypeId::UtxoId(utxo_id) => format!("coin with utxo_id: `{utxo_id:x}`"),
CoinTypeId::Nonce(nonce) => format!("message with nonce: `{nonce}`"),
};
Err(Error::Transaction(transaction::Reason::Validation(
format!(
"{msg} was submitted recently in a transaction - attempting to spend it again will result in an error. Wallet address: `{addr}`, asset id: `{asset_id}`"
),
)))
} else {
Ok(())
}
}
#[cfg(feature = "coin-cache")]
async fn submit<T: Transaction>(&self, tx: T) -> Result<TxId> {
let consensus_parameters = self.consensus_parameters().await?;
let base_asset_id = consensus_parameters.base_asset_id();
let used_utxos = tx.used_coins(base_asset_id);
self.check_inputs_already_in_cache(&used_utxos).await?;
let tx_id = self.uncached_client().submit(&tx.into()).await?;
self.coins_cache.lock().await.insert_multiple(used_utxos);
Ok(tx_id)
}
pub async fn tx_status(&self, tx_id: &TxId) -> Result<TxStatus> {
Ok(self
.uncached_client()
.transaction_status(tx_id)
.await?
.into())
}
pub async fn subscribe_transaction_status<'a>(
&'a self,
tx_id: &'a TxId,
include_preconfirmation: bool,
) -> Result<impl futures::Stream<Item = Result<TxStatus>> + 'a> {
let stream = self
.uncached_client()
.subscribe_transaction_status(tx_id, include_preconfirmation)
.await?;
Ok(stream.map(|status| status.map(Into::into).map_err(Into::into)))
}
pub async fn chain_info(&self) -> Result<ChainInfo> {
Ok(self.uncached_client().chain_info().await?.into())
}
pub async fn consensus_parameters(&self) -> Result<ConsensusParameters> {
self.cached_client.consensus_parameters().await
}
pub async fn node_info(&self) -> Result<NodeInfo> {
Ok(self.cached_client.node_info().await?.into())
}
pub async fn latest_gas_price(&self) -> Result<LatestGasPrice> {
Ok(self.uncached_client().latest_gas_price().await?)
}
pub async fn estimate_gas_price(&self, block_horizon: u32) -> Result<EstimateGasPrice> {
Ok(self
.uncached_client()
.estimate_gas_price(block_horizon)
.await?)
}
pub async fn dry_run(&self, tx: impl Transaction) -> Result<TxStatus> {
let [tx_status] = self
.uncached_client()
.dry_run(Transactions::new().insert(tx).as_slice())
.await?
.into_iter()
.map(Into::into)
.collect::<Vec<_>>()
.try_into()
.expect("should have only one element");
Ok(tx_status)
}
pub async fn dry_run_multiple(
&self,
transactions: Transactions,
) -> Result<Vec<(TxId, TxStatus)>> {
Ok(self
.uncached_client()
.dry_run(transactions.as_slice())
.await?
.into_iter()
.map(|execution_status| (execution_status.id, execution_status.into()))
.collect())
}
pub async fn dry_run_opt(
&self,
tx: impl Transaction,
utxo_validation: bool,
gas_price: Option<u64>,
at_height: Option<BlockHeight>,
) -> Result<TxStatus> {
let [tx_status] = self
.uncached_client()
.dry_run_opt(
Transactions::new().insert(tx).as_slice(),
Some(utxo_validation),
gas_price,
at_height,
)
.await?
.into_iter()
.map(Into::into)
.collect::<Vec<_>>()
.try_into()
.expect("should have only one element");
Ok(tx_status)
}
pub async fn dry_run_opt_multiple(
&self,
transactions: Transactions,
utxo_validation: bool,
gas_price: Option<u64>,
at_height: Option<BlockHeight>,
) -> Result<Vec<(TxId, TxStatus)>> {
Ok(self
.uncached_client()
.dry_run_opt(
transactions.as_slice(),
Some(utxo_validation),
gas_price,
at_height,
)
.await?
.into_iter()
.map(|execution_status| (execution_status.id, execution_status.into()))
.collect())
}
/// Gets all unspent coins owned by address `from`, with asset ID `asset_id`.
pub async fn get_coins(&self, from: &Address, asset_id: AssetId) -> Result<Vec<Coin>> {
let mut coins: Vec<Coin> = vec![];
let mut cursor = None;
loop {
let response = self
.uncached_client()
.coins(
from,
Some(&asset_id),
PaginationRequest {
cursor: cursor.clone(),
results: NUM_RESULTS_PER_REQUEST,
direction: PageDirection::Forward,
},
)
.await?;
if response.results.is_empty() {
break;
}
coins.extend(response.results.into_iter().map(Into::into));
cursor = response.cursor;
}
Ok(coins)
}
async fn request_coins_to_spend(&self, filter: ResourceFilter) -> Result<Vec<CoinType>> {
let queries = filter.resource_queries();
let consensus_parameters = self.consensus_parameters().await?;
let base_asset_id = *consensus_parameters.base_asset_id();
let res = self
.uncached_client()
.coins_to_spend(
&filter.owner(),
queries.spend_query(base_asset_id),
queries.exclusion_query(),
)
.await?
.into_iter()
.flatten()
.map(CoinType::from)
.collect();
Ok(res)
}
/// Get some spendable coins of asset `asset_id` for address `from` that add up at least to
/// amount `amount`. The returned coins (UTXOs) are actual coins that can be spent. The number
/// of coins (UXTOs) is optimized to prevent dust accumulation.
#[cfg(not(feature = "coin-cache"))]
pub async fn get_spendable_resources(&self, filter: ResourceFilter) -> Result<Vec<CoinType>> {
self.request_coins_to_spend(filter).await
}
/// Get some spendable coins of asset `asset_id` for address `from` that add up at least to
/// amount `amount`. The returned coins (UTXOs) are actual coins that can be spent. The number
/// of coins (UXTOs) is optimized to prevent dust accumulation.
/// Coins that were recently submitted inside a tx will be ignored from the results.
#[cfg(feature = "coin-cache")]
pub async fn get_spendable_resources(
&self,
mut filter: ResourceFilter,
) -> Result<Vec<CoinType>> {
self.extend_filter_with_cached(&mut filter).await?;
self.request_coins_to_spend(filter).await
}
#[cfg(feature = "coin-cache")]
async fn extend_filter_with_cached(&self, filter: &mut ResourceFilter) -> Result<()> {
let consensus_parameters = self.consensus_parameters().await?;
let mut cache = self.coins_cache.lock().await;
let asset_id = filter
.asset_id
.unwrap_or(*consensus_parameters.base_asset_id());
let used_coins = cache.get_active(&(filter.from, asset_id));
let excluded_utxos = used_coins
.iter()
.filter_map(|coin_id| match coin_id {
CoinTypeId::UtxoId(utxo_id) => Some(utxo_id),
_ => None,
})
.cloned()
.collect::<Vec<_>>();
let excluded_message_nonces = used_coins
.iter()
.filter_map(|coin_id| match coin_id {
CoinTypeId::Nonce(nonce) => Some(nonce),
_ => None,
})
.cloned()
.collect::<Vec<_>>();
filter.excluded_utxos.extend(excluded_utxos);
filter
.excluded_message_nonces
.extend(excluded_message_nonces);
Ok(())
}
/// Get the balance of all spendable coins `asset_id` for address `address`. This is different
/// from getting coins because we are just returning a number (the sum of UTXOs amount) instead
/// of the UTXOs.
pub async fn get_asset_balance(&self, address: &Address, asset_id: &AssetId) -> Result<u128> {
Ok(self
.uncached_client()
.balance(address, Some(asset_id))
.await?)
}
/// Get the balance of all spendable coins `asset_id` for contract with id `contract_id`.
pub async fn get_contract_asset_balance(
&self,
contract_id: &ContractId,
asset_id: &AssetId,
) -> Result<u64> {
Ok(self
.uncached_client()
.contract_balance(contract_id, Some(asset_id))
.await?)
}
/// Get all the spendable balances of all assets for address `address`. This is different from
/// getting the coins because we are only returning the numbers (the sum of UTXOs coins amount
/// for each asset id) and not the UTXOs coins themselves
pub async fn get_balances(&self, address: &Address) -> Result<HashMap<String, u128>> {
let mut balances = HashMap::new();
let mut register_balances = |results: Vec<_>| {
let pairs = results.into_iter().map(
|Balance {
owner: _,
amount,
asset_id,
}| (asset_id.to_string(), amount),
);
balances.extend(pairs);
};
let indexation_flags = self.cached_client.node_info().await?.indexation;
if indexation_flags.balances {
let mut cursor = None;
loop {
let pagination = PaginationRequest {
cursor: cursor.clone(),
results: NUM_RESULTS_PER_REQUEST,
direction: PageDirection::Forward,
};
let response = self.uncached_client().balances(address, pagination).await?;
if response.results.is_empty() {
break;
}
register_balances(response.results);
cursor = response.cursor;
}
} else {
let pagination = PaginationRequest {
cursor: None,
results: 9999,
direction: PageDirection::Forward,
};
let response = self.uncached_client().balances(address, pagination).await?;
register_balances(response.results)
}
Ok(balances)
}
/// Get all balances of all assets for the contract with id `contract_id`.
pub async fn get_contract_balances(
&self,
contract_id: &ContractId,
) -> Result<HashMap<AssetId, u64>> {
let mut contract_balances = HashMap::new();
let mut cursor = None;
loop {
let response = self
.uncached_client()
.contract_balances(
contract_id,
PaginationRequest {
cursor: cursor.clone(),
results: NUM_RESULTS_PER_REQUEST,
direction: PageDirection::Forward,
},
)
.await?;
if response.results.is_empty() {
break;
}
contract_balances.extend(response.results.into_iter().map(
|ContractBalance {
contract: _,
amount,
asset_id,
}| (asset_id, amount),
));
cursor = response.cursor;
}
Ok(contract_balances)
}
pub async fn get_transaction_by_id(&self, tx_id: &TxId) -> Result<Option<TransactionResponse>> {
Ok(self
.uncached_client()
.transaction(tx_id)
.await?
.map(Into::into))
}
pub async fn get_transactions(
&self,
request: PaginationRequest<String>,
) -> Result<PaginatedResult<TransactionResponse, String>> {
let pr = self.uncached_client().transactions(request).await?;
Ok(PaginatedResult {
cursor: pr.cursor,
results: pr.results.into_iter().map(Into::into).collect(),
has_next_page: pr.has_next_page,
has_previous_page: pr.has_previous_page,
})
}
// Get transaction(s) by owner
pub async fn get_transactions_by_owner(
&self,
owner: &Address,
request: PaginationRequest<String>,
) -> Result<PaginatedResult<TransactionResponse, String>> {
let pr = self
.uncached_client()
.transactions_by_owner(owner, request)
.await?;
Ok(PaginatedResult {
cursor: pr.cursor,
results: pr.results.into_iter().map(Into::into).collect(),
has_next_page: pr.has_next_page,
has_previous_page: pr.has_previous_page,
})
}
pub async fn latest_block_height(&self) -> Result<u32> {
Ok(self.chain_info().await?.latest_block.header.height)
}
pub async fn latest_block_time(&self) -> Result<Option<DateTime<Utc>>> {
Ok(self.chain_info().await?.latest_block.header.time)
}
pub async fn produce_blocks(
&self,
blocks_to_produce: u32,
start_time: Option<DateTime<Utc>>,
) -> Result<u32> {
let start_time = start_time.map(|time| Tai64::from_unix(time.timestamp()).0);
Ok(self
.uncached_client()
.produce_blocks(blocks_to_produce, start_time)
.await?
.into())
}
pub async fn block(&self, block_id: &Bytes32) -> Result<Option<Block>> {
Ok(self
.uncached_client()
.block(block_id)
.await?
.map(Into::into))
}
pub async fn block_by_height(&self, height: BlockHeight) -> Result<Option<Block>> {
Ok(self
.uncached_client()
.block_by_height(height)
.await?
.map(Into::into))
}
// - Get block(s)
pub async fn get_blocks(
&self,
request: PaginationRequest<String>,
) -> Result<PaginatedResult<Block, String>> {
let pr = self.uncached_client().blocks(request).await?;
Ok(PaginatedResult {
cursor: pr.cursor,
results: pr.results.into_iter().map(Into::into).collect(),
has_next_page: pr.has_next_page,
has_previous_page: pr.has_previous_page,
})
}
pub async fn estimate_transaction_cost<T: Transaction>(
&self,
tx: T,
tolerance: Option<f64>,
block_horizon: Option<u32>,
) -> Result<TransactionCost> {
let block_horizon = block_horizon.unwrap_or(DEFAULT_GAS_ESTIMATION_BLOCK_HORIZON);
let tolerance = tolerance.unwrap_or(DEFAULT_GAS_ESTIMATION_TOLERANCE);
let EstimateGasPrice { gas_price, .. } = self.estimate_gas_price(block_horizon).await?;
let tx_status = self.dry_run_opt(tx.clone(), false, None, None).await?;
let total_gas = Self::apply_tolerance(tx_status.total_gas(), tolerance);
let total_fee = Self::apply_tolerance(tx_status.total_fee(), tolerance);
let receipts = tx_status.take_receipts();
Ok(TransactionCost {
gas_price,
metered_bytes_size: tx.metered_bytes_size() as u64,
total_fee,
total_gas,
script_gas: Self::get_script_gas_used(&receipts),
})
}
fn apply_tolerance(value: u64, tolerance: f64) -> u64 {
(value as f64 * (1.0 + tolerance)).ceil() as u64
}
fn get_script_gas_used(receipts: &[Receipt]) -> u64 {
receipts
.iter()
.rfind(|r| matches!(r, Receipt::ScriptResult { .. }))
.map(|script_result| {
script_result
.gas_used()
.expect("could not retrieve gas used from ScriptResult")
})
.unwrap_or(0)
}
pub async fn get_messages(&self, from: &Address) -> Result<Vec<Message>> {
let mut messages = Vec::new();
let mut cursor = None;
loop {
let response = self
.uncached_client()
.messages(
Some(from),
PaginationRequest {
cursor: cursor.clone(),
results: NUM_RESULTS_PER_REQUEST,
direction: PageDirection::Forward,
},
)
.await?;
if response.results.is_empty() {
break;
}
messages.extend(response.results.into_iter().map(Into::into));
cursor = response.cursor;
}
Ok(messages)
}
pub async fn get_message_proof(
&self,
tx_id: &TxId,
nonce: &Nonce,
commit_block_id: Option<&Bytes32>,
commit_block_height: Option<u32>,
) -> Result<MessageProof> {
self.uncached_client()
.message_proof(
tx_id,
nonce,
commit_block_id,
commit_block_height.map(Into::into),
)
.await
.map(Into::into)
.map_err(Into::into)
}
pub async fn is_user_account(&self, address: impl Into<Bytes32>) -> Result<bool> {
self.uncached_client()
.is_user_account(*address.into())
.await
}
pub fn with_retry_config(mut self, retry_config: RetryConfig) -> Self {
self.uncached_client_mut().set_retry_config(retry_config);
self
}
pub async fn contract_exists(&self, contract_id: &ContractId) -> Result<bool> {
Ok(self.uncached_client().contract_exists(contract_id).await?)
}
fn uncached_client(&self) -> &RetryableClient {
self.cached_client.inner()
}
fn uncached_client_mut(&mut self) -> &mut RetryableClient {
self.cached_client.inner_mut()
}
}
#[cfg_attr(not(target_arch = "wasm32"), async_trait::async_trait)]
impl DryRunner for Provider {
async fn dry_run(&self, tx: FuelTransaction) -> Result<DryRun> {
let [tx_execution_status] = self
.uncached_client()
.dry_run_opt(&vec![tx], Some(false), Some(0), None)
.await?
.try_into()
.expect("should have only one element");
let receipts = tx_execution_status.result.receipts();
let script_gas = Self::get_script_gas_used(receipts);
let variable_outputs = receipts
.iter()
.filter(
|receipt| matches!(receipt, Receipt::TransferOut { amount, .. } if *amount != 0),
)
.count();
let succeeded = matches!(
tx_execution_status.result,
TransactionExecutionResult::Success { .. }
);
let dry_run = DryRun {
succeeded,
script_gas,
variable_outputs,
};
Ok(dry_run)
}
async fn estimate_gas_price(&self, block_horizon: u32) -> Result<u64> {
Ok(self.estimate_gas_price(block_horizon).await?.gas_price)
}
async fn consensus_parameters(&self) -> Result<ConsensusParameters> {
Provider::consensus_parameters(self).await
}
async fn estimate_predicates(
&self,
tx: &FuelTransaction,
_latest_chain_executor_version: Option<u32>,
) -> Result<FuelTransaction> {
Ok(self.uncached_client().estimate_predicates(tx).await?)
}
}
| rust | Apache-2.0 | 865e00c295de8b4a0a1ef7ac926c3c8266d5151b | 2026-01-04T15:31:59.450823Z | false |
FuelLabs/fuels-rs | https://github.com/FuelLabs/fuels-rs/blob/865e00c295de8b4a0a1ef7ac926c3c8266d5151b/packages/fuels-accounts/src/account.rs | packages/fuels-accounts/src/account.rs | use std::collections::HashMap;
use async_trait::async_trait;
use fuel_core_client::client::pagination::{PaginatedResult, PaginationRequest};
use fuel_tx::{Output, TxId, TxPointer, UtxoId};
use fuels_core::types::{
Address, AssetId, Bytes32, ContractId, Nonce,
coin::Coin,
coin_type::CoinType,
coin_type_id::CoinTypeId,
errors::{Context, Result},
input::Input,
message::Message,
transaction::{Transaction, TxPolicies},
transaction_builders::{BuildableTransaction, ScriptTransactionBuilder, TransactionBuilder},
transaction_response::TransactionResponse,
tx_response::TxResponse,
tx_status::Success,
};
use crate::{
accounts_utils::{
add_base_change_if_needed, available_base_assets_and_amount, calculate_missing_base_amount,
extract_message_nonce, split_into_utxo_ids_and_nonces,
},
provider::{Provider, ResourceFilter},
};
#[derive(Clone, Debug)]
pub struct WithdrawToBaseResponse {
pub tx_status: Success,
pub tx_id: TxId,
pub nonce: Nonce,
}
#[cfg_attr(not(target_arch = "wasm32"), async_trait)]
pub trait ViewOnlyAccount: Send + Sync {
fn address(&self) -> Address;
fn try_provider(&self) -> Result<&Provider>;
async fn get_transactions(
&self,
request: PaginationRequest<String>,
) -> Result<PaginatedResult<TransactionResponse, String>> {
Ok(self
.try_provider()?
.get_transactions_by_owner(&self.address(), request)
.await?)
}
/// Gets all unspent coins of asset `asset_id` owned by the account.
async fn get_coins(&self, asset_id: AssetId) -> Result<Vec<Coin>> {
Ok(self
.try_provider()?
.get_coins(&self.address(), asset_id)
.await?)
}
/// Get the balance of all spendable coins `asset_id` for address `address`. This is different
/// from getting coins because we are just returning a number (the sum of UTXOs amount) instead
/// of the UTXOs.
async fn get_asset_balance(&self, asset_id: &AssetId) -> Result<u128> {
self.try_provider()?
.get_asset_balance(&self.address(), asset_id)
.await
}
/// Gets all unspent messages owned by the account.
async fn get_messages(&self) -> Result<Vec<Message>> {
Ok(self.try_provider()?.get_messages(&self.address()).await?)
}
/// Get all the spendable balances of all assets for the account. This is different from getting
/// the coins because we are only returning the sum of UTXOs coins amount and not the UTXOs
/// coins themselves.
async fn get_balances(&self) -> Result<HashMap<String, u128>> {
self.try_provider()?.get_balances(&self.address()).await
}
/// Get some spendable resources (coins and messages) of asset `asset_id` owned by the account
/// that add up at least to amount `amount`. The returned coins (UTXOs) are actual coins that
/// can be spent. The number of UXTOs is optimized to prevent dust accumulation.
async fn get_spendable_resources(
&self,
asset_id: AssetId,
amount: u128,
excluded_coins: Option<Vec<CoinTypeId>>,
) -> Result<Vec<CoinType>> {
let (excluded_utxos, excluded_message_nonces) =
split_into_utxo_ids_and_nonces(excluded_coins);
let filter = ResourceFilter {
from: self.address(),
asset_id: Some(asset_id),
amount,
excluded_utxos,
excluded_message_nonces,
};
self.try_provider()?.get_spendable_resources(filter).await
}
/// Returns a vector containing the output coin and change output given an asset and amount
fn get_asset_outputs_for_amount(
&self,
to: Address,
asset_id: AssetId,
amount: u64,
) -> Vec<Output> {
vec![
Output::coin(to, amount, asset_id),
// Note that the change will be computed by the node.
// Here we only have to tell the node who will own the change and its asset ID.
Output::change(self.address(), 0, asset_id),
]
}
/// Returns a vector consisting of `Input::Coin`s and `Input::Message`s for the given
/// asset ID and amount.
async fn get_asset_inputs_for_amount(
&self,
asset_id: AssetId,
amount: u128,
excluded_coins: Option<Vec<CoinTypeId>>,
) -> Result<Vec<Input>>;
/// Add base asset inputs to the transaction to cover the estimated fee
/// and add a change output for the base asset if needed.
/// Requires contract inputs to be at the start of the transactions inputs vec
/// so that their indexes are retained
async fn adjust_for_fee<Tb: TransactionBuilder + Sync>(
&self,
tb: &mut Tb,
used_base_amount: u128,
) -> Result<()> {
let provider = self.try_provider()?;
let consensus_parameters = provider.consensus_parameters().await?;
let base_asset_id = consensus_parameters.base_asset_id();
let (base_assets, base_amount) = available_base_assets_and_amount(tb, base_asset_id);
let missing_base_amount =
calculate_missing_base_amount(tb, base_amount, used_base_amount, provider).await?;
if missing_base_amount > 0 {
let new_base_inputs = self
.get_asset_inputs_for_amount(
*consensus_parameters.base_asset_id(),
missing_base_amount,
Some(base_assets),
)
.await
.with_context(|| {
format!("failed to get base asset ({base_asset_id}) inputs with amount: `{missing_base_amount}`")
})?;
tb.inputs_mut().extend(new_base_inputs);
};
add_base_change_if_needed(tb, self.address(), *consensus_parameters.base_asset_id());
Ok(())
}
}
#[cfg_attr(not(target_arch = "wasm32"), async_trait)]
pub trait Account: ViewOnlyAccount {
// Add signatures to the builder if the underlying account is a wallet
fn add_witnesses<Tb: TransactionBuilder>(&self, _tb: &mut Tb) -> Result<()> {
Ok(())
}
/// Transfer funds from this account to another `Address`.
/// Fails if amount for asset ID is larger than address's spendable coins.
/// Returns the transaction ID that was sent and the list of receipts.
async fn transfer(
&self,
to: Address,
amount: u64,
asset_id: AssetId,
tx_policies: TxPolicies,
) -> Result<TxResponse> {
let provider = self.try_provider()?;
let inputs = self
.get_asset_inputs_for_amount(asset_id, amount.into(), None)
.await?;
let outputs = self.get_asset_outputs_for_amount(to, asset_id, amount);
let mut tx_builder =
ScriptTransactionBuilder::prepare_transfer(inputs, outputs, tx_policies);
self.add_witnesses(&mut tx_builder)?;
let consensus_parameters = provider.consensus_parameters().await?;
let used_base_amount = if asset_id == *consensus_parameters.base_asset_id() {
amount.into()
} else {
0
};
self.adjust_for_fee(&mut tx_builder, used_base_amount)
.await
.context("failed to adjust inputs to cover for missing base asset")?;
let tx = tx_builder.build(provider).await?;
let tx_id = tx.id(consensus_parameters.chain_id());
let tx_status = provider.send_transaction_and_await_commit(tx).await?;
Ok(TxResponse {
tx_status: tx_status.take_success_checked(None)?,
tx_id,
})
}
/// Unconditionally transfers `balance` of type `asset_id` to
/// the contract at `to`.
/// Fails if balance for `asset_id` is larger than this account's spendable balance.
/// Returns the corresponding transaction ID and the list of receipts.
///
/// CAUTION !!!
///
/// This will transfer coins to a contract, possibly leading
/// to the PERMANENT LOSS OF COINS if not used with care.
async fn force_transfer_to_contract(
&self,
to: ContractId,
balance: u64,
asset_id: AssetId,
tx_policies: TxPolicies,
) -> Result<TxResponse> {
let provider = self.try_provider()?;
let zeroes = Bytes32::zeroed();
let mut inputs = vec![Input::contract(
UtxoId::new(zeroes, 0),
zeroes,
zeroes,
TxPointer::default(),
to,
)];
inputs.extend(
self.get_asset_inputs_for_amount(asset_id, balance.into(), None)
.await?,
);
let outputs = vec![
Output::contract(0, zeroes, zeroes),
Output::change(self.address(), 0, asset_id),
];
// Build transaction and sign it
let mut tb = ScriptTransactionBuilder::prepare_contract_transfer(
to,
balance,
asset_id,
inputs,
outputs,
tx_policies,
);
let consensus_parameters = provider.consensus_parameters().await?;
let used_base_amount = if asset_id == *consensus_parameters.base_asset_id() {
balance
} else {
0
};
self.add_witnesses(&mut tb)?;
self.adjust_for_fee(&mut tb, used_base_amount.into())
.await
.context("failed to adjust inputs to cover for missing base asset")?;
let tx = tb.build(provider).await?;
let consensus_parameters = provider.consensus_parameters().await?;
let tx_id = tx.id(consensus_parameters.chain_id());
let tx_status = provider.send_transaction_and_await_commit(tx).await?;
Ok(TxResponse {
tx_status: tx_status.take_success_checked(None)?,
tx_id,
})
}
/// Withdraws an amount of the base asset to
/// an address on the base chain.
/// Returns the transaction ID, message ID and the list of receipts.
async fn withdraw_to_base_layer(
&self,
to: Address,
amount: u64,
tx_policies: TxPolicies,
) -> Result<WithdrawToBaseResponse> {
let provider = self.try_provider()?;
let consensus_parameters = provider.consensus_parameters().await?;
let inputs = self
.get_asset_inputs_for_amount(*consensus_parameters.base_asset_id(), amount.into(), None)
.await?;
let mut tb = ScriptTransactionBuilder::prepare_message_to_output(
to,
amount,
inputs,
tx_policies,
*consensus_parameters.base_asset_id(),
);
self.add_witnesses(&mut tb)?;
self.adjust_for_fee(&mut tb, amount.into())
.await
.context("failed to adjust inputs to cover for missing base asset")?;
let tx = tb.build(provider).await?;
let tx_id = tx.id(consensus_parameters.chain_id());
let tx_status = provider.send_transaction_and_await_commit(tx).await?;
let success = tx_status.take_success_checked(None)?;
let nonce = extract_message_nonce(&success.receipts)
.expect("MessageId could not be retrieved from tx receipts.");
Ok(WithdrawToBaseResponse {
tx_status: success,
tx_id,
nonce,
})
}
}
#[cfg(test)]
mod tests {
use std::str::FromStr;
use fuel_crypto::{Message, SecretKey, Signature};
use fuel_tx::{Address, ConsensusParameters, Output, Transaction as FuelTransaction};
use fuels_core::{
traits::Signer,
types::{DryRun, DryRunner, transaction::Transaction},
};
use super::*;
use crate::signers::private_key::PrivateKeySigner;
#[derive(Default)]
struct MockDryRunner {
c_param: ConsensusParameters,
}
#[cfg_attr(not(target_arch = "wasm32"), async_trait)]
impl DryRunner for MockDryRunner {
async fn dry_run(&self, _: FuelTransaction) -> Result<DryRun> {
Ok(DryRun {
succeeded: true,
script_gas: 0,
variable_outputs: 0,
})
}
async fn consensus_parameters(&self) -> Result<ConsensusParameters> {
Ok(self.c_param.clone())
}
async fn estimate_gas_price(&self, _block_header: u32) -> Result<u64> {
Ok(0)
}
async fn estimate_predicates(
&self,
_: &FuelTransaction,
_: Option<u32>,
) -> Result<FuelTransaction> {
unimplemented!()
}
}
#[tokio::test]
async fn sign_tx_and_verify() -> std::result::Result<(), Box<dyn std::error::Error>> {
// ANCHOR: sign_tb
let secret = SecretKey::from_str(
"5f70feeff1f229e4a95e1056e8b4d80d0b24b565674860cc213bdb07127ce1b1",
)?;
let signer = PrivateKeySigner::new(secret);
// Set up a transaction
let mut tb = {
let input_coin = Input::ResourceSigned {
resource: CoinType::Coin(Coin {
amount: 10000000,
owner: signer.address(),
..Default::default()
}),
};
let output_coin = Output::coin(
Address::from_str(
"0xc7862855b418ba8f58878db434b21053a61a2025209889cc115989e8040ff077",
)?,
1,
Default::default(),
);
let change = Output::change(signer.address(), 0, Default::default());
ScriptTransactionBuilder::prepare_transfer(
vec![input_coin],
vec![output_coin, change],
Default::default(),
)
};
// Add `Signer` to the transaction builder
tb.add_signer(signer.clone())?;
// ANCHOR_END: sign_tb
let tx = tb.build(MockDryRunner::default()).await?; // Resolve signatures and add corresponding witness indexes
// Extract the signature from the tx witnesses
let bytes = <[u8; Signature::LEN]>::try_from(tx.witnesses().first().unwrap().as_ref())?;
let tx_signature = Signature::from_bytes(bytes);
// Sign the transaction manually
let message = Message::from_bytes(*tx.id(0.into()));
let signature = signer.sign(message).await?;
// Check if the signatures are the same
assert_eq!(signature, tx_signature);
// Check if the signature is what we expect it to be
assert_eq!(
signature,
Signature::from_str(
"faa616776a1c336ef6257f7cb0cb5cd932180e2d15faba5f17481dae1cbcaf314d94617bd900216a6680bccb1ea62438e4ca93b0d5733d33788ef9d79cc24e9f"
)?
);
// Recover the address that signed the transaction
let recovered_address = signature.recover(&message)?;
assert_eq!(*signer.address(), *recovered_address.hash());
// Verify signature
signature.verify(&recovered_address, &message)?;
Ok(())
}
}
| rust | Apache-2.0 | 865e00c295de8b4a0a1ef7ac926c3c8266d5151b | 2026-01-04T15:31:59.450823Z | false |
FuelLabs/fuels-rs | https://github.com/FuelLabs/fuels-rs/blob/865e00c295de8b4a0a1ef7ac926c3c8266d5151b/packages/fuels-accounts/src/signers/fake.rs | packages/fuels-accounts/src/signers/fake.rs | use async_trait::async_trait;
use fuel_crypto::{Message, Signature};
use fuels_core::{
traits::Signer,
types::{Address, errors::Result},
};
use super::private_key::PrivateKeySigner;
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct FakeSigner {
address: Address,
}
impl From<PrivateKeySigner> for FakeSigner {
fn from(signer: PrivateKeySigner) -> Self {
Self {
address: signer.address(),
}
}
}
impl FakeSigner {
pub fn new(address: Address) -> Self {
Self { address }
}
}
#[cfg_attr(target_arch = "wasm32", async_trait(?Send))]
#[cfg_attr(not(target_arch = "wasm32"), async_trait)]
impl Signer for FakeSigner {
async fn sign(&self, _message: Message) -> Result<Signature> {
Ok(Signature::default())
}
fn address(&self) -> Address {
self.address
}
}
| rust | Apache-2.0 | 865e00c295de8b4a0a1ef7ac926c3c8266d5151b | 2026-01-04T15:31:59.450823Z | false |
FuelLabs/fuels-rs | https://github.com/FuelLabs/fuels-rs/blob/865e00c295de8b4a0a1ef7ac926c3c8266d5151b/packages/fuels-accounts/src/signers/private_key.rs | packages/fuels-accounts/src/signers/private_key.rs | use async_trait::async_trait;
use fuel_crypto::{Message, PublicKey, SecretKey, Signature};
use fuels_core::{
traits::Signer,
types::{Address, errors::Result},
};
use rand::{CryptoRng, Rng, RngCore};
use zeroize::{Zeroize, ZeroizeOnDrop};
/// Generates a random mnemonic phrase given a random number generator and the number of words to
/// generate, `count`.
pub fn generate_mnemonic_phrase<R: Rng>(rng: &mut R, count: usize) -> Result<String> {
Ok(fuel_crypto::generate_mnemonic_phrase(rng, count)?)
}
#[derive(Clone, Zeroize, ZeroizeOnDrop)]
pub struct PrivateKeySigner {
private_key: SecretKey,
#[zeroize(skip)]
address: Address,
}
impl std::fmt::Debug for PrivateKeySigner {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("PrivateKeySigner")
.field("private_key", &"REDACTED")
.field("address", &self.address)
.finish()
}
}
impl PrivateKeySigner {
pub fn new(private_key: SecretKey) -> Self {
let public = PublicKey::from(&private_key);
let address = Address::from(*public.hash());
Self {
private_key,
address,
}
}
pub fn random(rng: &mut (impl CryptoRng + RngCore)) -> Self {
Self::new(SecretKey::random(rng))
}
pub fn address(&self) -> Address {
self.address
}
pub fn secret_key(&self) -> SecretKey {
self.private_key
}
}
#[cfg_attr(target_arch = "wasm32", async_trait(?Send))]
#[cfg_attr(not(target_arch = "wasm32"), async_trait)]
impl Signer for PrivateKeySigner {
async fn sign(&self, message: Message) -> Result<Signature> {
let sig = Signature::sign(&self.private_key, &message);
Ok(sig)
}
fn address(&self) -> Address {
self.address
}
}
#[cfg(test)]
mod tests {
use std::str::FromStr;
use rand::{SeedableRng, rngs::StdRng};
use super::*;
use crate::signers::derivation::DEFAULT_DERIVATION_PATH;
#[tokio::test]
async fn mnemonic_generation() -> Result<()> {
let mnemonic = generate_mnemonic_phrase(&mut rand::thread_rng(), 12)?;
let _wallet = PrivateKeySigner::new(SecretKey::new_from_mnemonic_phrase_with_path(
&mnemonic,
DEFAULT_DERIVATION_PATH,
)?);
Ok(())
}
#[tokio::test]
async fn sign_and_verify() -> Result<()> {
// ANCHOR: sign_message
let mut rng = StdRng::seed_from_u64(2322u64);
let mut secret_seed = [0u8; 32];
rng.fill_bytes(&mut secret_seed);
let secret = secret_seed.as_slice().try_into()?;
// Create a signer using the private key created above.
let signer = PrivateKeySigner::new(secret);
let message = Message::new("my message".as_bytes());
let signature = signer.sign(message).await?;
// Check if signature is what we expect it to be
assert_eq!(
signature,
Signature::from_str(
"0x8eeb238db1adea4152644f1cd827b552dfa9ab3f4939718bb45ca476d167c6512a656f4d4c7356bfb9561b14448c230c6e7e4bd781df5ee9e5999faa6495163d"
)?
);
// Recover the public key that signed the message
let recovered_pub_key: PublicKey = signature.recover(&message)?;
assert_eq!(*signer.address, *recovered_pub_key.hash());
// Verify signature
signature.verify(&recovered_pub_key, &message)?;
// ANCHOR_END: sign_message
Ok(())
}
}
| rust | Apache-2.0 | 865e00c295de8b4a0a1ef7ac926c3c8266d5151b | 2026-01-04T15:31:59.450823Z | false |
FuelLabs/fuels-rs | https://github.com/FuelLabs/fuels-rs/blob/865e00c295de8b4a0a1ef7ac926c3c8266d5151b/packages/fuels-accounts/src/signers/kms.rs | packages/fuels-accounts/src/signers/kms.rs | #[cfg(feature = "signer-aws-kms")]
pub mod aws;
#[cfg(feature = "signer-google-kms")]
pub mod google;
mod signature_utils {
use fuel_crypto::{Message, Signature};
use fuels_core::types::errors::{Error, Result};
use k256::{
PublicKey as K256PublicKey,
ecdsa::{RecoveryId, Signature as K256Signature, VerifyingKey},
};
pub fn normalize_signature(
signature_der: &[u8],
message: Message,
expected_pubkey: &K256PublicKey,
error_prefix: &str,
) -> Result<(K256Signature, RecoveryId)> {
let signature = K256Signature::from_der(signature_der)
.map_err(|_| Error::Other(format!("{error_prefix}: Invalid DER signature")))?;
let normalized_sig = signature.normalize_s().unwrap_or(signature);
let recovery_id =
determine_recovery_id(&normalized_sig, message, expected_pubkey, error_prefix)?;
Ok((normalized_sig, recovery_id))
}
pub fn determine_recovery_id(
sig: &K256Signature,
message: Message,
expected_pubkey: &K256PublicKey,
error_prefix: &str,
) -> Result<RecoveryId> {
let recid_even = RecoveryId::new(false, false);
let recid_odd = RecoveryId::new(true, false);
let expected_verifying_key: VerifyingKey = expected_pubkey.into();
let recovered_even = VerifyingKey::recover_from_prehash(&*message, sig, recid_even);
let recovered_odd = VerifyingKey::recover_from_prehash(&*message, sig, recid_odd);
if recovered_even
.map(|r| r == expected_verifying_key)
.unwrap_or(false)
{
Ok(recid_even)
} else if recovered_odd
.map(|r| r == expected_verifying_key)
.unwrap_or(false)
{
Ok(recid_odd)
} else {
Err(Error::Other(format!(
"{error_prefix}: Invalid signature (could not recover correct public key)"
)))
}
}
pub fn convert_to_fuel_signature(
signature: K256Signature,
recovery_id: RecoveryId,
) -> Signature {
let recovery_byte = recovery_id.is_y_odd() as u8;
let mut bytes: [u8; 64] = signature.to_bytes().into();
bytes[32] = (recovery_byte << 7) | (bytes[32] & 0x7F);
Signature::from_bytes(bytes)
}
}
| rust | Apache-2.0 | 865e00c295de8b4a0a1ef7ac926c3c8266d5151b | 2026-01-04T15:31:59.450823Z | false |
FuelLabs/fuels-rs | https://github.com/FuelLabs/fuels-rs/blob/865e00c295de8b4a0a1ef7ac926c3c8266d5151b/packages/fuels-accounts/src/signers/kms/aws.rs | packages/fuels-accounts/src/signers/kms/aws.rs | use async_trait::async_trait;
pub use aws_config;
pub use aws_sdk_kms;
use aws_sdk_kms::{
Client,
primitives::Blob,
types::{KeySpec, MessageType, SigningAlgorithmSpec},
};
use fuel_crypto::{Message, PublicKey, Signature};
use fuels_core::{
traits::Signer,
types::{
Address,
errors::{Error, Result},
},
};
use k256::{PublicKey as K256PublicKey, pkcs8::DecodePublicKey};
use super::signature_utils;
const AWS_KMS_ERROR_PREFIX: &str = "AWS KMS Error";
const EXPECTED_KEY_SPEC: KeySpec = KeySpec::EccSecgP256K1;
#[derive(Clone, Debug)]
pub struct AwsKmsSigner {
key_id: String,
client: Client,
public_key_der: Vec<u8>,
fuel_address: Address,
}
impl AwsKmsSigner {
pub async fn new(key_id: impl Into<String>, client: &Client) -> Result<Self> {
let key_id: String = key_id.into();
Self::validate_key_spec(client, &key_id).await?;
let public_key = Self::retrieve_public_key(client, &key_id).await?;
let fuel_address = Self::derive_fuel_address(&public_key)?;
Ok(Self {
key_id,
client: client.clone(),
public_key_der: public_key,
fuel_address,
})
}
async fn validate_key_spec(client: &Client, key_id: &str) -> Result<()> {
let response = client
.get_public_key()
.key_id(key_id)
.send()
.await
.map_err(format_aws_error)?;
let key_spec = response.key_spec;
match key_spec {
Some(EXPECTED_KEY_SPEC) => Ok(()),
other => Err(Error::Other(format!(
"{AWS_KMS_ERROR_PREFIX}: Invalid key type {other:?}, expected {EXPECTED_KEY_SPEC:?}"
))),
}
}
async fn retrieve_public_key(client: &Client, key_id: &str) -> Result<Vec<u8>> {
let response = client
.get_public_key()
.key_id(key_id)
.send()
.await
.map_err(format_aws_error)?;
response
.public_key()
.map(|blob| blob.as_ref().to_vec())
.ok_or_else(|| {
Error::Other(format!("{AWS_KMS_ERROR_PREFIX}: Empty public key response"))
})
}
fn derive_fuel_address(public_key: &[u8]) -> Result<Address> {
let k256_key = K256PublicKey::from_public_key_der(public_key)
.map_err(|_| Error::Other(format!("{AWS_KMS_ERROR_PREFIX}: Invalid DER encoding")))?;
let fuel_public_key = PublicKey::from(k256_key);
Ok(Address::from(*fuel_public_key.hash()))
}
async fn request_kms_signature(&self, message: Message) -> Result<Vec<u8>> {
let response = self
.client
.sign()
.key_id(&self.key_id)
.signing_algorithm(SigningAlgorithmSpec::EcdsaSha256)
.message_type(MessageType::Digest)
.message(Blob::new(message.as_ref().to_vec()))
.send()
.await
.map_err(|err| {
Error::Other(format!("{AWS_KMS_ERROR_PREFIX}: Signing failed - {err}"))
})?;
response
.signature
.map(|blob| blob.into_inner())
.ok_or_else(|| {
Error::Other(format!("{AWS_KMS_ERROR_PREFIX}: Empty signature response"))
})
}
pub fn key_id(&self) -> &String {
&self.key_id
}
pub fn public_key(&self) -> &Vec<u8> {
&self.public_key_der
}
}
#[async_trait]
impl Signer for AwsKmsSigner {
async fn sign(&self, message: Message) -> Result<Signature> {
let signature_der = self.request_kms_signature(message).await?;
let k256_key = K256PublicKey::from_public_key_der(&self.public_key_der).map_err(|_| {
Error::Other(format!("{AWS_KMS_ERROR_PREFIX}: Invalid cached public key"))
})?;
let (normalized_sig, recovery_id) = signature_utils::normalize_signature(
&signature_der,
message,
&k256_key,
AWS_KMS_ERROR_PREFIX,
)?;
Ok(signature_utils::convert_to_fuel_signature(
normalized_sig,
recovery_id,
))
}
fn address(&self) -> Address {
self.fuel_address
}
}
fn format_aws_error(err: impl std::fmt::Display) -> Error {
Error::Other(format!("{AWS_KMS_ERROR_PREFIX}: {err}"))
}
| rust | Apache-2.0 | 865e00c295de8b4a0a1ef7ac926c3c8266d5151b | 2026-01-04T15:31:59.450823Z | false |
FuelLabs/fuels-rs | https://github.com/FuelLabs/fuels-rs/blob/865e00c295de8b4a0a1ef7ac926c3c8266d5151b/packages/fuels-accounts/src/signers/kms/google.rs | packages/fuels-accounts/src/signers/kms/google.rs | use async_trait::async_trait;
use fuel_crypto::{Message, PublicKey, Signature};
use fuels_core::{
traits::Signer,
types::{
Address,
errors::{Error, Result},
},
};
pub use google_cloud_kms;
use google_cloud_kms::{
client::Client,
grpc::kms::v1::{
AsymmetricSignRequest, Digest, GetPublicKeyRequest,
crypto_key_version::CryptoKeyVersionAlgorithm::EcSignSecp256k1Sha256,
digest::Digest::Sha256,
},
};
use k256::{PublicKey as K256PublicKey, pkcs8::DecodePublicKey};
use super::signature_utils;
const GOOGLE_KMS_ERROR_PREFIX: &str = "Google KMS Error";
#[derive(Clone, Debug)]
pub struct GoogleKmsSigner {
key_path: String,
client: Client,
public_key_pem: String,
fuel_address: Address,
}
#[derive(Debug, Clone)]
pub struct CryptoKeyVersionName {
pub project_id: String,
pub location: String,
pub key_ring: String,
pub key_id: String,
pub key_version: String,
}
impl CryptoKeyVersionName {
pub fn new(
project_id: impl Into<String>,
location: impl Into<String>,
key_ring: impl Into<String>,
key_id: impl Into<String>,
key_version: impl Into<String>,
) -> Self {
Self {
project_id: project_id.into(),
location: location.into(),
key_ring: key_ring.into(),
key_id: key_id.into(),
key_version: key_version.into(),
}
}
}
impl std::fmt::Display for CryptoKeyVersionName {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
f,
"projects/{}/locations/{}/keyRings/{}/cryptoKeys/{}/cryptoKeyVersions/{}",
self.project_id, self.location, self.key_ring, self.key_id, self.key_version
)
}
}
impl GoogleKmsSigner {
pub async fn new(key_path: impl Into<String>, client: &Client) -> Result<Self> {
let key_path: String = key_path.into();
let public_key_pem = Self::retrieve_public_key(client, &key_path).await?;
let fuel_address = Self::derive_fuel_address(&public_key_pem)?;
Ok(Self {
key_path,
client: client.clone(),
public_key_pem,
fuel_address,
})
}
async fn retrieve_public_key(client: &Client, key_path: &str) -> Result<String> {
let request = GetPublicKeyRequest {
name: key_path.to_string(),
};
let response = client
.get_public_key(request, None)
.await
.map_err(|e| format_gcp_error(format!("Failed to get public key: {}", e)))?;
if response.algorithm != EcSignSecp256k1Sha256 as i32 {
return Err(Error::Other(format!(
"{GOOGLE_KMS_ERROR_PREFIX}: Invalid key algorithm: {}, expected EC_SIGN_SECP256K1_SHA256",
response.algorithm
)));
}
Ok(response.pem)
}
fn derive_fuel_address(pem: &str) -> Result<Address> {
let k256_key = K256PublicKey::from_public_key_pem(pem).map_err(|_| {
Error::Other(format!("{GOOGLE_KMS_ERROR_PREFIX}: Invalid PEM encoding"))
})?;
let fuel_public_key = PublicKey::from(k256_key);
Ok(Address::from(*fuel_public_key.hash()))
}
async fn request_gcp_signature(&self, message: Message) -> Result<Vec<u8>> {
let digest = Digest {
digest: Some(Sha256(message.as_ref().to_vec())),
};
let request = AsymmetricSignRequest {
name: self.key_path.clone(),
digest: Some(digest),
digest_crc32c: None,
..AsymmetricSignRequest::default()
};
let response = self
.client
.asymmetric_sign(request, None)
.await
.map_err(|e| format_gcp_error(format!("Signing failed: {}", e)))?;
if response.signature.is_empty() {
return Err(Error::Other(format!(
"{GOOGLE_KMS_ERROR_PREFIX}: Empty signature response"
)));
}
Ok(response.signature)
}
pub fn key_path(&self) -> &String {
&self.key_path
}
pub fn public_key(&self) -> &String {
&self.public_key_pem
}
}
#[async_trait]
impl Signer for GoogleKmsSigner {
async fn sign(&self, message: Message) -> Result<Signature> {
let signature_der = self.request_gcp_signature(message).await?;
let k256_key = K256PublicKey::from_public_key_pem(&self.public_key_pem).map_err(|_| {
Error::Other(format!(
"{GOOGLE_KMS_ERROR_PREFIX}: Invalid cached public key"
))
})?;
let (normalized_sig, recovery_id) = signature_utils::normalize_signature(
&signature_der,
message,
&k256_key,
GOOGLE_KMS_ERROR_PREFIX,
)?;
Ok(signature_utils::convert_to_fuel_signature(
normalized_sig,
recovery_id,
))
}
fn address(&self) -> Address {
self.fuel_address
}
}
fn format_gcp_error(err: impl std::fmt::Display) -> Error {
Error::Other(format!("{GOOGLE_KMS_ERROR_PREFIX}: {err}"))
}
| rust | Apache-2.0 | 865e00c295de8b4a0a1ef7ac926c3c8266d5151b | 2026-01-04T15:31:59.450823Z | false |
FuelLabs/fuels-rs | https://github.com/FuelLabs/fuels-rs/blob/865e00c295de8b4a0a1ef7ac926c3c8266d5151b/packages/fuels-accounts/src/provider/retry_util.rs | packages/fuels-accounts/src/provider/retry_util.rs | use std::{fmt::Debug, future::Future, num::NonZeroU32, time::Duration};
use fuels_core::types::errors::{Result, error};
/// A set of strategies to control retry intervals between attempts.
///
/// The `Backoff` enum defines different strategies for managing intervals between retry attempts.
/// Each strategy allows you to customize the waiting time before a new attempt based on the
/// number of attempts made.
///
/// # Variants
///
/// - `Linear(Duration)`: Increases the waiting time linearly with each attempt.
/// - `Exponential(Duration)`: Doubles the waiting time with each attempt.
/// - `Fixed(Duration)`: Uses a constant waiting time between attempts.
///
/// # Examples
///
/// ```rust
/// use std::time::Duration;
/// use fuels_accounts::provider::Backoff;
///
/// let linear_backoff = Backoff::Linear(Duration::from_secs(2));
/// let exponential_backoff = Backoff::Exponential(Duration::from_secs(1));
/// let fixed_backoff = Backoff::Fixed(Duration::from_secs(5));
/// ```
//ANCHOR: backoff
#[derive(Debug, Clone)]
pub enum Backoff {
Linear(Duration),
Exponential(Duration),
Fixed(Duration),
}
//ANCHOR_END: backoff
impl Default for Backoff {
fn default() -> Self {
Backoff::Linear(Duration::from_millis(10))
}
}
impl Backoff {
pub fn wait_duration(&self, attempt: u32) -> Duration {
match self {
Backoff::Linear(base_duration) => *base_duration * (attempt + 1),
Backoff::Exponential(base_duration) => *base_duration * 2u32.pow(attempt),
Backoff::Fixed(interval) => *interval,
}
}
}
/// Configuration for controlling retry behavior.
///
/// The `RetryConfig` struct encapsulates the configuration parameters for controlling the retry behavior
/// of asynchronous actions. It includes the maximum number of attempts and the interval strategy from
/// the `Backoff` enum that determines how much time to wait between retry attempts.
///
/// # Fields
///
/// - `max_attempts`: The maximum number of attempts before giving up.
/// - `interval`: The chosen interval strategy from the `Backoff` enum.
///
/// # Examples
///
/// ```rust
/// use std::num::NonZeroUsize;
/// use std::time::Duration;
/// use fuels_accounts::provider::{Backoff, RetryConfig};
///
/// let max_attempts = 5;
/// let interval_strategy = Backoff::Exponential(Duration::from_secs(1));
///
/// let retry_config = RetryConfig::new(max_attempts, interval_strategy).unwrap();
/// ```
// ANCHOR: retry_config
#[derive(Clone, Debug)]
pub struct RetryConfig {
max_attempts: NonZeroU32,
interval: Backoff,
}
// ANCHOR_END: retry_config
impl RetryConfig {
pub fn new(max_attempts: u32, interval: Backoff) -> Result<Self> {
let max_attempts = NonZeroU32::new(max_attempts)
.ok_or_else(|| error!(Other, "`max_attempts` must be greater than `0`"))?;
Ok(RetryConfig {
max_attempts,
interval,
})
}
}
impl Default for RetryConfig {
fn default() -> Self {
Self {
max_attempts: NonZeroU32::new(1).expect("should not fail"),
interval: Default::default(),
}
}
}
/// Retries an asynchronous action with customizable retry behavior.
///
/// This function takes an asynchronous action represented by a closure `action`.
/// The action is executed repeatedly with backoff and retry logic based on the
/// provided `retry_config` and the `should_retry` condition.
///
/// The `action` closure should return a `Future` that resolves to a `Result<T, K>`,
/// where `T` represents the success type and `K` represents the error type.
///
/// # Parameters
///
/// - `action`: The asynchronous action to be retried.
/// - `retry_config`: A reference to the retry configuration.
/// - `should_retry`: A closure that determines whether to retry based on the result.
///
/// # Return
///
/// Returns `Ok(T)` if the action succeeds without requiring further retries.
/// Returns `Err(Error)` if the maximum number of attempts is reached and the action
/// still fails. If a retryable error occurs during the attempts, the error will
/// be returned if the `should_retry` condition allows further retries.
pub(crate) async fn retry<Fut, T, ShouldRetry>(
mut action: impl FnMut() -> Fut,
retry_config: &RetryConfig,
should_retry: ShouldRetry,
) -> T
where
Fut: Future<Output = T>,
ShouldRetry: Fn(&T) -> bool,
{
let mut last_result = None;
for attempt in 0..retry_config.max_attempts.into() {
let result = action().await;
if should_retry(&result) {
last_result = Some(result)
} else {
return result;
}
tokio::time::sleep(retry_config.interval.wait_duration(attempt)).await;
}
last_result.expect("should not happen")
}
#[cfg(test)]
mod tests {
mod retry_until {
use std::time::{Duration, Instant};
use fuels_core::types::errors::{Result, error};
use tokio::sync::Mutex;
use crate::provider::{Backoff, RetryConfig, retry_util};
#[tokio::test]
async fn returns_last_received_response() -> Result<()> {
// given
let err_msgs = ["err1", "err2", "err3"];
let number_of_attempts = Mutex::new(0usize);
let will_always_fail = || async {
let msg = err_msgs[*number_of_attempts.lock().await];
*number_of_attempts.lock().await += 1;
msg
};
let should_retry_fn = |_res: &_| -> bool { true };
let retry_options = RetryConfig::new(3, Backoff::Linear(Duration::from_millis(10)))?;
// when
let response =
retry_util::retry(will_always_fail, &retry_options, should_retry_fn).await;
// then
assert_eq!(response, "err3");
Ok(())
}
#[tokio::test]
async fn stops_retrying_when_predicate_is_satisfied() -> Result<()> {
// given
let values = Mutex::new(vec![1, 2, 3]);
let will_always_fail = || async { values.lock().await.pop().unwrap() };
let should_retry_fn = |res: &i32| *res != 2;
let retry_options = RetryConfig::new(3, Backoff::Linear(Duration::from_millis(10)))?;
// when
let response =
retry_util::retry(will_always_fail, &retry_options, should_retry_fn).await;
// then
assert_eq!(response, 2);
Ok(())
}
#[tokio::test]
async fn retry_respects_delay_between_attempts_fixed() -> Result<()> {
// given
let timestamps: Mutex<Vec<Instant>> = Mutex::new(vec![]);
let will_fail_and_record_timestamp = || async {
timestamps.lock().await.push(Instant::now());
Result::<()>::Err(error!(Other, "error"))
};
let should_retry_fn = |_res: &_| -> bool { true };
let retry_options = RetryConfig::new(3, Backoff::Fixed(Duration::from_millis(100)))?;
// when
let _ = retry_util::retry(
will_fail_and_record_timestamp,
&retry_options,
should_retry_fn,
)
.await;
// then
let timestamps_vec = timestamps.lock().await.clone();
let timestamps_spaced_out_at_least_100_mills = timestamps_vec
.iter()
.zip(timestamps_vec.iter().skip(1))
.all(|(current_timestamp, the_next_timestamp)| {
the_next_timestamp.duration_since(*current_timestamp)
>= Duration::from_millis(100)
});
assert!(
timestamps_spaced_out_at_least_100_mills,
"retry did not wait for the specified time between attempts"
);
Ok(())
}
#[tokio::test]
async fn retry_respects_delay_between_attempts_linear() -> Result<()> {
// given
let timestamps: Mutex<Vec<Instant>> = Mutex::new(vec![]);
let will_fail_and_record_timestamp = || async {
timestamps.lock().await.push(Instant::now());
Result::<()>::Err(error!(Other, "error"))
};
let should_retry_fn = |_res: &_| -> bool { true };
let retry_options = RetryConfig::new(3, Backoff::Linear(Duration::from_millis(100)))?;
// when
let _ = retry_util::retry(
will_fail_and_record_timestamp,
&retry_options,
should_retry_fn,
)
.await;
// then
let timestamps_vec = timestamps.lock().await.clone();
let timestamps_spaced_out_at_least_100_mills = timestamps_vec
.iter()
.zip(timestamps_vec.iter().skip(1))
.enumerate()
.all(|(attempt, (current_timestamp, the_next_timestamp))| {
the_next_timestamp.duration_since(*current_timestamp)
>= (Duration::from_millis(100) * (attempt + 1) as u32)
});
assert!(
timestamps_spaced_out_at_least_100_mills,
"retry did not wait for the specified time between attempts"
);
Ok(())
}
#[tokio::test]
async fn retry_respects_delay_between_attempts_exponential() -> Result<()> {
// given
let timestamps: Mutex<Vec<Instant>> = Mutex::new(vec![]);
let will_fail_and_record_timestamp = || async {
timestamps.lock().await.push(Instant::now());
Result::<()>::Err(error!(Other, "error"))
};
let should_retry_fn = |_res: &_| -> bool { true };
let retry_options =
RetryConfig::new(3, Backoff::Exponential(Duration::from_millis(100)))?;
// when
let _ = retry_util::retry(
will_fail_and_record_timestamp,
&retry_options,
should_retry_fn,
)
.await;
// then
let timestamps_vec = timestamps.lock().await.clone();
let timestamps_spaced_out_at_least_100_mills = timestamps_vec
.iter()
.zip(timestamps_vec.iter().skip(1))
.enumerate()
.all(|(attempt, (current_timestamp, the_next_timestamp))| {
the_next_timestamp.duration_since(*current_timestamp)
>= (Duration::from_millis(100) * (2_usize.pow((attempt) as u32)) as u32)
});
assert!(
timestamps_spaced_out_at_least_100_mills,
"retry did not wait for the specified time between attempts"
);
Ok(())
}
}
}
| rust | Apache-2.0 | 865e00c295de8b4a0a1ef7ac926c3c8266d5151b | 2026-01-04T15:31:59.450823Z | false |
FuelLabs/fuels-rs | https://github.com/FuelLabs/fuels-rs/blob/865e00c295de8b4a0a1ef7ac926c3c8266d5151b/packages/fuels-accounts/src/provider/cache.rs | packages/fuels-accounts/src/provider/cache.rs | use std::{sync::Arc, time::Duration};
use async_trait::async_trait;
use chrono::{DateTime, Utc};
use fuel_core_client::client::types::NodeInfo;
use fuel_tx::ConsensusParameters;
use fuels_core::types::errors::Result;
use tokio::sync::RwLock;
#[cfg_attr(test, mockall::automock)]
#[async_trait]
pub trait CacheableRpcs {
async fn consensus_parameters(&self) -> Result<ConsensusParameters>;
async fn node_info(&self) -> Result<NodeInfo>;
}
trait Clock {
fn now(&self) -> DateTime<Utc>;
}
#[derive(Debug, Clone)]
pub struct TtlConfig {
pub consensus_parameters: Duration,
}
impl Default for TtlConfig {
fn default() -> Self {
TtlConfig {
consensus_parameters: Duration::from_secs(60),
}
}
}
#[derive(Debug, Clone)]
struct Dated<T> {
value: T,
date: DateTime<Utc>,
}
impl<T> Dated<T> {
fn is_stale(&self, now: DateTime<Utc>, ttl: Duration) -> bool {
self.date + ttl < now
}
}
#[derive(Debug, Clone, Copy)]
pub struct SystemClock;
impl Clock for SystemClock {
fn now(&self) -> DateTime<Utc> {
Utc::now()
}
}
#[derive(Debug, Clone)]
pub struct CachedClient<Client, Clock = SystemClock> {
client: Client,
ttl_config: TtlConfig,
cached_consensus_params: Arc<RwLock<Option<Dated<ConsensusParameters>>>>,
cached_node_info: Arc<RwLock<Option<Dated<NodeInfo>>>>,
clock: Clock,
}
impl<Client, Clock> CachedClient<Client, Clock> {
pub fn new(client: Client, ttl: TtlConfig, clock: Clock) -> Self {
Self {
client,
ttl_config: ttl,
cached_consensus_params: Default::default(),
cached_node_info: Default::default(),
clock,
}
}
pub fn set_ttl(&mut self, ttl: TtlConfig) {
self.ttl_config = ttl
}
pub fn inner(&self) -> &Client {
&self.client
}
pub fn inner_mut(&mut self) -> &mut Client {
&mut self.client
}
}
impl<Client, Clk> CachedClient<Client, Clk>
where
Client: CacheableRpcs,
{
pub async fn clear(&self) {
*self.cached_consensus_params.write().await = None;
}
}
#[async_trait]
impl<Client, Clk> CacheableRpcs for CachedClient<Client, Clk>
where
Clk: Clock + Send + Sync,
Client: CacheableRpcs + Send + Sync,
{
async fn consensus_parameters(&self) -> Result<ConsensusParameters> {
{
let read_lock = self.cached_consensus_params.read().await;
if let Some(entry) = read_lock.as_ref()
&& !entry.is_stale(self.clock.now(), self.ttl_config.consensus_parameters)
{
return Ok(entry.value.clone());
}
}
let mut write_lock = self.cached_consensus_params.write().await;
// because it could have been updated since we last checked
if let Some(entry) = write_lock.as_ref()
&& !entry.is_stale(self.clock.now(), self.ttl_config.consensus_parameters)
{
return Ok(entry.value.clone());
}
let fresh_parameters = self.client.consensus_parameters().await?;
*write_lock = Some(Dated {
value: fresh_parameters.clone(),
date: self.clock.now(),
});
Ok(fresh_parameters)
}
async fn node_info(&self) -> Result<NodeInfo> {
// must borrow from consensus_parameters to keep the change non-breaking
let ttl = self.ttl_config.consensus_parameters;
{
let read_lock = self.cached_node_info.read().await;
if let Some(entry) = read_lock.as_ref()
&& !entry.is_stale(self.clock.now(), ttl)
{
return Ok(entry.value.clone());
}
}
let mut write_lock = self.cached_node_info.write().await;
// because it could have been updated since we last checked
if let Some(entry) = write_lock.as_ref()
&& !entry.is_stale(self.clock.now(), ttl)
{
return Ok(entry.value.clone());
}
let fresh_node_info = self.client.node_info().await?;
*write_lock = Some(Dated {
value: fresh_node_info.clone(),
date: self.clock.now(),
});
Ok(fresh_node_info)
}
}
#[cfg(test)]
mod tests {
use std::sync::Mutex;
use fuel_core_client::client::schema::{
U64,
node_info::{IndexationFlags, TxPoolStats},
};
use fuel_types::ChainId;
use super::*;
#[derive(Clone, Default)]
struct TestClock {
time: Arc<Mutex<DateTime<Utc>>>,
}
impl TestClock {
fn update_time(&self, time: DateTime<Utc>) {
*self.time.lock().unwrap() = time;
}
}
impl Clock for TestClock {
fn now(&self) -> DateTime<Utc> {
*self.time.lock().unwrap()
}
}
#[tokio::test]
async fn initial_call_to_consensus_params_fwd_to_api() {
// given
let mut api = MockCacheableRpcs::new();
api.expect_consensus_parameters()
.once()
.return_once(|| Ok(ConsensusParameters::default()));
let sut = CachedClient::new(api, TtlConfig::default(), TestClock::default());
// when
let _consensus_params = sut.consensus_parameters().await.unwrap();
// then
// mock validates the call went through
}
#[tokio::test]
async fn new_call_to_consensus_params_cached() {
// given
let mut api = MockCacheableRpcs::new();
api.expect_consensus_parameters()
.once()
.return_once(|| Ok(ConsensusParameters::default()));
let sut = CachedClient::new(
api,
TtlConfig {
consensus_parameters: Duration::from_secs(10),
},
TestClock::default(),
);
let consensus_parameters = sut.consensus_parameters().await.unwrap();
// when
let second_call_consensus_params = sut.consensus_parameters().await.unwrap();
// then
// mock validates only one call
assert_eq!(consensus_parameters, second_call_consensus_params);
}
#[tokio::test]
async fn if_ttl_expired_cache_is_updated() {
// given
let original_consensus_params = ConsensusParameters::default();
let changed_consensus_params = {
let mut params = original_consensus_params.clone();
params.set_chain_id(ChainId::new(99));
params
};
let api = {
let mut api = MockCacheableRpcs::new();
let original_consensus_params = original_consensus_params.clone();
let changed_consensus_params = changed_consensus_params.clone();
api.expect_consensus_parameters()
.once()
.return_once(move || Ok(original_consensus_params));
api.expect_consensus_parameters()
.once()
.return_once(move || Ok(changed_consensus_params));
api
};
let clock = TestClock::default();
let start_time = clock.now();
let sut = CachedClient::new(
api,
TtlConfig {
consensus_parameters: Duration::from_secs(10),
},
clock.clone(),
);
let consensus_parameters = sut.consensus_parameters().await.unwrap();
clock.update_time(start_time + Duration::from_secs(11));
// when
let second_call_consensus_params = sut.consensus_parameters().await.unwrap();
// then
// mock validates two calls made
assert_eq!(consensus_parameters, original_consensus_params);
assert_eq!(second_call_consensus_params, changed_consensus_params);
}
#[tokio::test]
async fn clear_cache_clears_consensus_params_cache() {
// given
let first_params = ConsensusParameters::default();
let second_params = {
let mut params = ConsensusParameters::default();
params.set_chain_id(ChainId::new(1234));
params
};
let api = {
let mut api = MockCacheableRpcs::new();
let first_clone = first_params.clone();
api.expect_consensus_parameters()
.times(1)
.return_once(move || Ok(first_clone));
let second_clone = second_params.clone();
api.expect_consensus_parameters()
.times(1)
.return_once(move || Ok(second_clone));
api
};
let clock = TestClock::default();
let sut = CachedClient::new(api, TtlConfig::default(), clock.clone());
let result1 = sut.consensus_parameters().await.unwrap();
// when
sut.clear().await;
// then
let result2 = sut.consensus_parameters().await.unwrap();
assert_eq!(result1, first_params);
assert_eq!(result2, second_params);
}
fn dummy_node_info() -> NodeInfo {
NodeInfo {
utxo_validation: true,
vm_backtrace: false,
max_tx: u64::MAX,
max_gas: u64::MAX,
max_size: u64::MAX,
max_depth: u64::MAX,
node_version: "0.0.1".to_string(),
indexation: IndexationFlags {
balances: true,
coins_to_spend: true,
asset_metadata: true,
},
tx_pool_stats: TxPoolStats {
tx_count: U64(1),
total_gas: U64(1),
total_size: U64(1),
},
}
}
#[tokio::test]
async fn initial_call_to_node_info_fwd_to_api() {
// given
let mut api = MockCacheableRpcs::new();
api.expect_node_info()
.once()
.return_once(|| Ok(dummy_node_info()));
let sut = CachedClient::new(api, TtlConfig::default(), TestClock::default());
// when
let _node_info = sut.node_info().await.unwrap();
// then
// The mock verifies that the API call was made.
}
#[tokio::test]
async fn new_call_to_node_info_cached() {
// given
let mut api = MockCacheableRpcs::new();
api.expect_node_info()
.once()
.return_once(|| Ok(dummy_node_info()));
let sut = CachedClient::new(
api,
TtlConfig {
consensus_parameters: Duration::from_secs(10),
},
TestClock::default(),
);
let first_node_info = sut.node_info().await.unwrap();
// when: second call should return the cached value
let second_node_info = sut.node_info().await.unwrap();
// then: only one API call should have been made and the values are equal
assert_eq!(first_node_info, second_node_info);
}
#[tokio::test]
async fn if_ttl_expired_node_info_cache_is_updated() {
// given
let original_node_info = dummy_node_info();
let changed_node_info = NodeInfo {
node_version: "changed".to_string(),
..dummy_node_info()
};
let api = {
let mut api = MockCacheableRpcs::new();
let original_clone = original_node_info.clone();
api.expect_node_info()
.times(1)
.return_once(move || Ok(original_clone));
let changed_clone = changed_node_info.clone();
api.expect_node_info()
.times(1)
.return_once(move || Ok(changed_clone));
api
};
let clock = TestClock::default();
let start_time = clock.now();
let sut = CachedClient::new(
api,
TtlConfig {
consensus_parameters: Duration::from_secs(10),
},
clock.clone(),
);
let first_call = sut.node_info().await.unwrap();
// Advance time past the TTL.
clock.update_time(start_time + Duration::from_secs(11));
// when: a new API call should be triggered because the TTL expired
let second_call = sut.node_info().await.unwrap();
// then
assert_eq!(first_call, original_node_info);
assert_eq!(second_call, changed_node_info);
}
}
| rust | Apache-2.0 | 865e00c295de8b4a0a1ef7ac926c3c8266d5151b | 2026-01-04T15:31:59.450823Z | false |
FuelLabs/fuels-rs | https://github.com/FuelLabs/fuels-rs/blob/865e00c295de8b4a0a1ef7ac926c3c8266d5151b/packages/fuels-accounts/src/provider/retryable_client.rs | packages/fuels-accounts/src/provider/retryable_client.rs | use std::{future::Future, io};
use async_trait::async_trait;
use custom_queries::{ContractExistsQuery, IsUserAccountQuery, IsUserAccountVariables};
use cynic::QueryBuilder;
use fuel_core_client::client::{
FuelClient,
pagination::{PaginatedResult, PaginationRequest},
schema::contract::ContractByIdArgs,
types::{
Balance, Blob, Block, ChainInfo, Coin, CoinType, ContractBalance, Message, MessageProof,
NodeInfo, TransactionResponse, TransactionStatus,
gas_price::{EstimateGasPrice, LatestGasPrice},
primitives::{BlockId, TransactionId},
},
};
use fuel_core_types::services::executor::TransactionExecutionStatus;
use fuel_tx::{BlobId, ConsensusParameters, Transaction, TxId, UtxoId};
use fuel_types::{Address, AssetId, BlockHeight, ContractId, Nonce};
use fuels_core::types::errors::{Error, Result, error};
use futures::Stream;
use super::{
cache::CacheableRpcs,
supported_versions::{self, VersionCompatibility},
};
use crate::provider::{RetryConfig, retry_util};
#[derive(Debug, thiserror::Error)]
pub(crate) enum RequestError {
#[error("io error: {0}")]
IO(String),
}
type RequestResult<T> = std::result::Result<T, RequestError>;
impl From<RequestError> for Error {
fn from(e: RequestError) -> Self {
Error::Provider(e.to_string())
}
}
#[derive(Debug, Clone)]
pub(crate) struct RetryableClient {
client: FuelClient,
url: String,
retry_config: RetryConfig,
prepend_warning: Option<String>,
}
#[async_trait]
impl CacheableRpcs for RetryableClient {
async fn consensus_parameters(&self) -> Result<ConsensusParameters> {
Ok(self.chain_info().await?.consensus_parameters)
}
async fn node_info(&self) -> Result<NodeInfo> {
Ok(self.node_info().await?)
}
}
impl RetryableClient {
pub(crate) async fn connect(url: impl AsRef<str>, retry_config: RetryConfig) -> Result<Self> {
let url = url.as_ref().to_string();
let client = FuelClient::new(&url).map_err(|e| error!(Provider, "{e}"))?;
let node_info = client.node_info().await?;
let warning = Self::version_compatibility_warning(&node_info)?;
Ok(Self {
client,
retry_config,
url,
prepend_warning: warning,
})
}
fn version_compatibility_warning(node_info: &NodeInfo) -> Result<Option<String>> {
let node_version = node_info
.node_version
.parse::<semver::Version>()
.map_err(|e| error!(Provider, "could not parse Fuel client version: {}", e))?;
let VersionCompatibility {
supported_version,
is_major_supported,
is_minor_supported,
..
} = supported_versions::compare_node_compatibility(node_version.clone());
let msg = if !is_major_supported || !is_minor_supported {
Some(format!(
"warning: the fuel node version to which this provider is connected has a semver incompatible version from the one the SDK was developed against. Connected node version: {node_version}, supported version: {supported_version}",
))
} else {
None
};
Ok(msg)
}
pub(crate) fn url(&self) -> &str {
&self.url
}
pub fn client(&self) -> &FuelClient {
&self.client
}
pub(crate) fn set_retry_config(&mut self, retry_config: RetryConfig) {
self.retry_config = retry_config;
}
async fn wrap<T, Fut>(&self, action: impl Fn() -> Fut) -> RequestResult<T>
where
Fut: Future<Output = io::Result<T>>,
{
retry_util::retry(action, &self.retry_config, |result| result.is_err())
.await
.map_err(|e| {
let msg = if let Some(warning) = &self.prepend_warning {
format!("{warning}. {e}")
} else {
e.to_string()
};
RequestError::IO(msg)
})
}
// DELEGATION START
pub async fn health(&self) -> RequestResult<bool> {
self.wrap(|| self.client.health()).await
}
pub async fn transaction(&self, id: &TxId) -> RequestResult<Option<TransactionResponse>> {
self.wrap(|| self.client.transaction(id)).await
}
pub(crate) async fn chain_info(&self) -> RequestResult<ChainInfo> {
self.wrap(|| self.client.chain_info()).await
}
pub async fn await_transaction_commit(&self, id: &TxId) -> RequestResult<TransactionStatus> {
self.wrap(|| self.client.await_transaction_commit(id)).await
}
pub async fn submit_and_await_commit(
&self,
tx: &Transaction,
) -> RequestResult<TransactionStatus> {
self.wrap(|| self.client.submit_and_await_commit(tx)).await
}
pub async fn submit_and_await_status<'a>(
&'a self,
tx: &'a Transaction,
include_preconfirmation: bool,
) -> RequestResult<impl Stream<Item = io::Result<TransactionStatus>> + 'a> {
self.wrap(|| {
self.client
.submit_and_await_status_opt(tx, None, Some(include_preconfirmation))
})
.await
}
pub async fn subscribe_transaction_status<'a>(
&'a self,
id: &'a TxId,
include_preconfirmation: bool,
) -> RequestResult<impl Stream<Item = io::Result<TransactionStatus>> + 'a> {
self.wrap(|| {
self.client
.subscribe_transaction_status_opt(id, Some(include_preconfirmation))
})
.await
}
pub async fn submit(&self, tx: &Transaction) -> RequestResult<TransactionId> {
self.wrap(|| self.client.submit(tx)).await
}
pub async fn transaction_status(&self, id: &TxId) -> RequestResult<TransactionStatus> {
self.wrap(|| self.client.transaction_status(id)).await
}
pub async fn node_info(&self) -> RequestResult<NodeInfo> {
self.wrap(|| self.client.node_info()).await
}
pub async fn blob(&self, blob_id: BlobId) -> RequestResult<Option<Blob>> {
self.wrap(|| self.client.blob(blob_id)).await
}
pub async fn blob_exists(&self, blob_id: BlobId) -> RequestResult<bool> {
self.wrap(|| self.client.blob_exists(blob_id)).await
}
pub async fn latest_gas_price(&self) -> RequestResult<LatestGasPrice> {
self.wrap(|| self.client.latest_gas_price()).await
}
pub async fn estimate_gas_price(&self, block_horizon: u32) -> RequestResult<EstimateGasPrice> {
self.wrap(|| self.client.estimate_gas_price(block_horizon))
.await
.map(Into::into)
}
pub async fn estimate_predicates(&self, tx: &Transaction) -> RequestResult<Transaction> {
self.wrap(|| async {
let mut new_tx = tx.clone();
self.client.estimate_predicates(&mut new_tx).await?;
Ok(new_tx)
})
.await
}
pub async fn dry_run(
&self,
tx: &[Transaction],
) -> RequestResult<Vec<TransactionExecutionStatus>> {
self.wrap(|| self.client.dry_run(tx)).await
}
pub async fn dry_run_opt(
&self,
tx: &[Transaction],
utxo_validation: Option<bool>,
gas_price: Option<u64>,
at_height: Option<BlockHeight>,
) -> RequestResult<Vec<TransactionExecutionStatus>> {
self.wrap(|| {
self.client
.dry_run_opt(tx, utxo_validation, gas_price, at_height)
})
.await
}
pub async fn coins(
&self,
owner: &Address,
asset_id: Option<&AssetId>,
request: PaginationRequest<String>,
) -> RequestResult<PaginatedResult<Coin, String>> {
self.wrap(move || self.client.coins(owner, asset_id, request.clone()))
.await
}
pub async fn coins_to_spend(
&self,
owner: &Address,
spend_query: Vec<(AssetId, u128, Option<u16>)>,
excluded_ids: Option<(Vec<UtxoId>, Vec<Nonce>)>,
) -> RequestResult<Vec<Vec<CoinType>>> {
self.wrap(move || {
self.client
.coins_to_spend(owner, spend_query.clone(), excluded_ids.clone())
})
.await
}
pub async fn balance(
&self,
owner: &Address,
asset_id: Option<&AssetId>,
) -> RequestResult<u128> {
self.wrap(|| self.client.balance(owner, asset_id)).await
}
pub async fn contract_balance(
&self,
id: &ContractId,
asset: Option<&AssetId>,
) -> RequestResult<u64> {
self.wrap(|| self.client.contract_balance(id, asset)).await
}
pub async fn contract_balances(
&self,
contract: &ContractId,
request: PaginationRequest<String>,
) -> RequestResult<PaginatedResult<ContractBalance, String>> {
self.wrap(|| self.client.contract_balances(contract, request.clone()))
.await
}
pub async fn balances(
&self,
owner: &Address,
request: PaginationRequest<String>,
) -> RequestResult<PaginatedResult<Balance, String>> {
self.wrap(|| self.client.balances(owner, request.clone()))
.await
}
pub async fn transactions(
&self,
request: PaginationRequest<String>,
) -> RequestResult<PaginatedResult<TransactionResponse, String>> {
self.wrap(|| self.client.transactions(request.clone()))
.await
}
pub async fn transactions_by_owner(
&self,
owner: &Address,
request: PaginationRequest<String>,
) -> RequestResult<PaginatedResult<TransactionResponse, String>> {
self.wrap(|| self.client.transactions_by_owner(owner, request.clone()))
.await
}
pub async fn produce_blocks(
&self,
blocks_to_produce: u32,
start_timestamp: Option<u64>,
) -> RequestResult<BlockHeight> {
self.wrap(|| {
self.client
.produce_blocks(blocks_to_produce, start_timestamp)
})
.await
}
pub async fn block(&self, id: &BlockId) -> RequestResult<Option<Block>> {
self.wrap(|| self.client.block(id)).await
}
pub async fn block_by_height(&self, height: BlockHeight) -> RequestResult<Option<Block>> {
self.wrap(|| self.client.block_by_height(height)).await
}
pub async fn blocks(
&self,
request: PaginationRequest<String>,
) -> RequestResult<PaginatedResult<Block, String>> {
self.wrap(|| self.client.blocks(request.clone())).await
}
pub async fn messages(
&self,
owner: Option<&Address>,
request: PaginationRequest<String>,
) -> RequestResult<PaginatedResult<Message, String>> {
self.wrap(|| self.client.messages(owner, request.clone()))
.await
}
/// Request a merkle proof of an output message.
pub async fn message_proof(
&self,
transaction_id: &TxId,
nonce: &Nonce,
commit_block_id: Option<&BlockId>,
commit_block_height: Option<BlockHeight>,
) -> RequestResult<MessageProof> {
self.wrap(|| {
self.client
.message_proof(transaction_id, nonce, commit_block_id, commit_block_height)
})
.await
}
pub async fn contract_exists(&self, contract_id: &ContractId) -> RequestResult<bool> {
self.wrap(|| {
let query = ContractExistsQuery::build(ContractByIdArgs {
id: (*contract_id).into(),
});
self.client.query(query)
})
.await
.map(|query| {
query
.contract
.map(|contract| ContractId::from(contract.id) == *contract_id)
.unwrap_or(false)
})
}
// DELEGATION END
pub async fn is_user_account(&self, address: [u8; 32]) -> Result<bool> {
let blob_id = BlobId::from(address);
let contract_id = ContractId::from(address);
let transaction_id = TransactionId::from(address);
let query = IsUserAccountQuery::build(IsUserAccountVariables {
blob_id: blob_id.into(),
contract_id: contract_id.into(),
transaction_id: transaction_id.into(),
});
let response = self.client.query(query).await?;
let is_resource = response.blob.is_some()
|| response.contract.is_some()
|| response.transaction.is_some();
Ok(!is_resource)
}
}
mod custom_queries {
use fuel_core_client::client::schema::{
BlobId, ContractId, TransactionId,
blob::BlobIdFragment,
contract::{ContractByIdArgsFields, ContractIdFragment},
schema,
tx::TransactionIdFragment,
};
#[derive(cynic::QueryVariables, Debug)]
pub struct IsUserAccountVariables {
pub blob_id: BlobId,
pub contract_id: ContractId,
pub transaction_id: TransactionId,
}
#[derive(cynic::QueryFragment, Debug)]
#[cynic(
graphql_type = "Query",
variables = "IsUserAccountVariables",
schema_path = "./src/schema/schema.sdl"
)]
pub struct IsUserAccountQuery {
#[arguments(id: $blob_id)]
pub blob: Option<BlobIdFragment>,
#[arguments(id: $contract_id)]
pub contract: Option<ContractIdFragment>,
#[arguments(id: $transaction_id)]
pub transaction: Option<TransactionIdFragment>,
}
#[derive(cynic::QueryFragment, Clone, Debug)]
#[cynic(
schema_path = "./src/schema/schema.sdl",
graphql_type = "Query",
variables = "ContractByIdArgs"
)]
pub struct ContractExistsQuery {
#[arguments(id: $id)]
pub contract: Option<ContractIdFragment>,
}
}
| rust | Apache-2.0 | 865e00c295de8b4a0a1ef7ac926c3c8266d5151b | 2026-01-04T15:31:59.450823Z | false |
FuelLabs/fuels-rs | https://github.com/FuelLabs/fuels-rs/blob/865e00c295de8b4a0a1ef7ac926c3c8266d5151b/packages/fuels-accounts/src/provider/supported_versions.rs | packages/fuels-accounts/src/provider/supported_versions.rs | use semver::Version;
use crate::provider::supported_fuel_core_version::SUPPORTED_FUEL_CORE_VERSION;
#[derive(Debug, PartialEq, Eq)]
pub(crate) struct VersionCompatibility {
pub(crate) supported_version: Version,
pub(crate) is_major_supported: bool,
pub(crate) is_minor_supported: bool,
pub(crate) is_patch_supported: bool,
}
pub(crate) fn compare_node_compatibility(network_version: Version) -> VersionCompatibility {
check_version_compatibility(network_version, SUPPORTED_FUEL_CORE_VERSION)
}
fn check_version_compatibility(
actual_version: Version,
expected_version: Version,
) -> VersionCompatibility {
let is_major_supported = expected_version.major == actual_version.major;
let is_minor_supported = expected_version.minor == actual_version.minor;
let is_patch_supported = expected_version.patch == actual_version.patch;
VersionCompatibility {
supported_version: expected_version,
is_major_supported,
is_minor_supported,
is_patch_supported,
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn should_validate_all_possible_version_mismatches() {
let expected_version = "0.1.2".parse::<Version>().unwrap();
assert_eq!(
check_version_compatibility("1.1.2".parse().unwrap(), expected_version.clone()),
VersionCompatibility {
is_major_supported: false,
is_minor_supported: true,
is_patch_supported: true,
supported_version: expected_version.clone()
}
);
assert_eq!(
check_version_compatibility("1.2.2".parse().unwrap(), expected_version.clone()),
VersionCompatibility {
is_major_supported: false,
is_minor_supported: false,
is_patch_supported: true,
supported_version: expected_version.clone()
}
);
assert_eq!(
check_version_compatibility("1.1.3".parse().unwrap(), expected_version.clone()),
VersionCompatibility {
is_major_supported: false,
is_minor_supported: true,
is_patch_supported: false,
supported_version: expected_version.clone()
}
);
assert_eq!(
check_version_compatibility("0.2.2".parse().unwrap(), expected_version.clone()),
VersionCompatibility {
is_major_supported: true,
is_minor_supported: false,
is_patch_supported: true,
supported_version: expected_version.clone()
}
);
assert_eq!(
check_version_compatibility("0.2.3".parse().unwrap(), expected_version.clone()),
VersionCompatibility {
is_major_supported: true,
is_minor_supported: false,
is_patch_supported: false,
supported_version: expected_version.clone()
}
);
assert_eq!(
check_version_compatibility("0.1.3".parse().unwrap(), expected_version.clone()),
VersionCompatibility {
is_major_supported: true,
is_minor_supported: true,
is_patch_supported: false,
supported_version: expected_version.clone()
}
);
assert_eq!(
check_version_compatibility("0.1.2".parse().unwrap(), expected_version.clone()),
VersionCompatibility {
is_major_supported: true,
is_minor_supported: true,
is_patch_supported: true,
supported_version: expected_version.clone()
}
);
}
}
| rust | Apache-2.0 | 865e00c295de8b4a0a1ef7ac926c3c8266d5151b | 2026-01-04T15:31:59.450823Z | false |
FuelLabs/fuels-rs | https://github.com/FuelLabs/fuels-rs/blob/865e00c295de8b4a0a1ef7ac926c3c8266d5151b/packages/fuels-accounts/src/provider/supported_fuel_core_version.rs | packages/fuels-accounts/src/provider/supported_fuel_core_version.rs | pub const SUPPORTED_FUEL_CORE_VERSION: semver::Version = semver::Version::new(0, 47, 1);
| rust | Apache-2.0 | 865e00c295de8b4a0a1ef7ac926c3c8266d5151b | 2026-01-04T15:31:59.450823Z | false |
FuelLabs/fuels-rs | https://github.com/FuelLabs/fuels-rs/blob/865e00c295de8b4a0a1ef7ac926c3c8266d5151b/packages/fuels-code-gen/src/lib.rs | packages/fuels-code-gen/src/lib.rs | pub use program_bindings::*;
pub mod error;
mod program_bindings;
pub mod utils;
| rust | Apache-2.0 | 865e00c295de8b4a0a1ef7ac926c3c8266d5151b | 2026-01-04T15:31:59.450823Z | false |
FuelLabs/fuels-rs | https://github.com/FuelLabs/fuels-rs/blob/865e00c295de8b4a0a1ef7ac926c3c8266d5151b/packages/fuels-code-gen/src/error.rs | packages/fuels-code-gen/src/error.rs | use std::{
fmt::{Debug, Display, Formatter},
io,
};
pub struct Error(pub String);
impl Error {
pub fn combine<T: Into<Self>>(self, err: T) -> Self {
error!("{} {}", self.0, err.into().0)
}
}
#[macro_export]
macro_rules! error {
($fmt_str: literal $(,$arg: expr)*) => {$crate::error::Error(format!($fmt_str,$($arg),*))}
}
pub use error;
pub type Result<T> = std::result::Result<T, Error>;
impl Debug for Error {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
write!(f, "{:?}", self.0)
}
}
impl Display for Error {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.0)
}
}
impl std::error::Error for Error {}
macro_rules! impl_from {
($($err_type:ty),*) => {
$(
impl From<$err_type> for self::Error {
fn from(err: $err_type) -> Self {
Self(err.to_string())
}
}
)*
}
}
impl_from!(
serde_json::Error,
io::Error,
proc_macro2::LexError,
fuel_abi_types::error::Error
);
| rust | Apache-2.0 | 865e00c295de8b4a0a1ef7ac926c3c8266d5151b | 2026-01-04T15:31:59.450823Z | false |
FuelLabs/fuels-rs | https://github.com/FuelLabs/fuels-rs/blob/865e00c295de8b4a0a1ef7ac926c3c8266d5151b/packages/fuels-code-gen/src/program_bindings.rs | packages/fuels-code-gen/src/program_bindings.rs | mod abigen;
mod custom_types;
mod generated_code;
mod resolved_type;
mod utils;
pub use abigen::{Abi, Abigen, AbigenTarget, ProgramType};
| rust | Apache-2.0 | 865e00c295de8b4a0a1ef7ac926c3c8266d5151b | 2026-01-04T15:31:59.450823Z | false |
FuelLabs/fuels-rs | https://github.com/FuelLabs/fuels-rs/blob/865e00c295de8b4a0a1ef7ac926c3c8266d5151b/packages/fuels-code-gen/src/utils.rs | packages/fuels-code-gen/src/utils.rs | pub use fuel_abi_types::utils::{TypePath, ident, safe_ident};
pub fn encode_fn_selector(name: &str) -> Vec<u8> {
let bytes = name.as_bytes().to_vec();
let len = bytes.len() as u64;
[len.to_be_bytes().to_vec(), bytes].concat()
}
| rust | Apache-2.0 | 865e00c295de8b4a0a1ef7ac926c3c8266d5151b | 2026-01-04T15:31:59.450823Z | false |
FuelLabs/fuels-rs | https://github.com/FuelLabs/fuels-rs/blob/865e00c295de8b4a0a1ef7ac926c3c8266d5151b/packages/fuels-code-gen/src/program_bindings/generated_code.rs | packages/fuels-code-gen/src/program_bindings/generated_code.rs | use std::collections::{HashMap, HashSet};
use itertools::Itertools;
use proc_macro2::{Ident, TokenStream};
use quote::quote;
use crate::utils::TypePath;
#[derive(Default, Debug)]
pub(crate) struct GeneratedCode {
top_level_code: TokenStream,
usable_types: HashSet<TypePath>,
code_in_mods: HashMap<Ident, GeneratedCode>,
no_std: bool,
}
impl GeneratedCode {
pub fn new(code: TokenStream, usable_types: HashSet<TypePath>, no_std: bool) -> Self {
Self {
top_level_code: code,
code_in_mods: HashMap::default(),
usable_types,
no_std,
}
}
fn prelude(&self) -> TokenStream {
let lib = if self.no_std {
quote! {::alloc}
} else {
quote! {::std}
};
quote! {
use ::core::{
clone::Clone,
convert::{Into, TryFrom, From},
iter::IntoIterator,
iter::Iterator,
marker::Sized,
panic,
};
use #lib::{string::ToString, format, vec, default::Default};
}
}
pub fn code(&self) -> TokenStream {
let top_level_code = &self.top_level_code;
let prelude = self.prelude();
let code_in_mods = self
.code_in_mods
.iter()
.sorted_by_key(|(mod_name, _)| {
// Sorted to make test expectations maintainable
*mod_name
})
.map(|(mod_name, generated_code)| {
let code = generated_code.code();
quote! {
#[allow(clippy::too_many_arguments)]
#[allow(clippy::disallowed_names)]
#[no_implicit_prelude]
pub mod #mod_name {
#prelude
#code
}
}
});
quote! {
#top_level_code
#(#code_in_mods)*
}
}
pub fn is_empty(&self) -> bool {
self.code().is_empty()
}
pub fn merge(mut self, another: GeneratedCode) -> Self {
self.top_level_code.extend(another.top_level_code);
self.usable_types.extend(another.usable_types);
for (mod_name, code) in another.code_in_mods {
let entry = self.code_in_mods.entry(mod_name).or_default();
*entry = std::mem::take(entry).merge(code);
}
self
}
pub fn wrap_in_mod(mut self, mod_name: impl Into<TypePath>) -> Self {
let mut parts = mod_name.into().take_parts();
parts.reverse();
for mod_name in parts {
self = self.wrap_in_single_mod(mod_name)
}
self
}
fn wrap_in_single_mod(self, mod_name: Ident) -> Self {
Self {
code_in_mods: HashMap::from([(mod_name, self)]),
..Default::default()
}
}
pub fn use_statements_for_uniquely_named_types(&self) -> TokenStream {
let type_paths = self
.types_with_unique_names()
.into_iter()
.filter(|type_path| type_path.has_multiple_parts());
quote! {
#(pub use #type_paths;)*
}
}
fn types_with_unique_names(&self) -> Vec<TypePath> {
self.code_in_mods
.iter()
.flat_map(|(mod_name, code)| {
code.types_with_unique_names()
.into_iter()
.map(|type_path| type_path.prepend(mod_name.into()))
.collect::<Vec<_>>()
})
.chain(self.usable_types.iter().cloned())
.sorted_by(|lhs, rhs| lhs.ident().cmp(&rhs.ident()))
.group_by(|e| e.ident().cloned())
.into_iter()
.filter_map(|(_, group)| {
let mut types = group.collect::<Vec<_>>();
(types.len() == 1).then_some(types.pop().unwrap())
})
.collect()
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::utils::ident;
#[test]
fn can_merge_top_level_code() {
// given
let struct_1 = given_some_struct_code("Struct1");
let struct_2 = given_some_struct_code("Struct2");
// when
let joined = struct_1.merge(struct_2);
// then
let expected_code = quote! {
struct Struct1;
struct Struct2;
};
assert_eq!(joined.code().to_string(), expected_code.to_string());
}
#[test]
fn wrapping_in_mod_updates_code() {
// given
let some_type = given_some_struct_code("SomeType");
// when
let wrapped_in_mod = some_type.wrap_in_mod(given_type_path("a_mod"));
// then
let expected_code = quote! {
#[allow(clippy::too_many_arguments)]
#[allow(clippy::disallowed_names)]
#[no_implicit_prelude]
pub mod a_mod {
use ::core::{
clone::Clone,
convert::{Into, TryFrom, From},
iter::IntoIterator,
iter::Iterator,
marker::Sized,
panic,
};
use ::std::{string::ToString, format, vec, default::Default};
struct SomeType;
}
};
assert_eq!(wrapped_in_mod.code().to_string(), expected_code.to_string());
}
#[test]
fn wrapping_in_mod_updates_use_statements() {
// given
let some_type = given_some_struct_code("SomeType");
let wrapped_in_mod = some_type.wrap_in_mod(given_type_path("a_mod"));
// when
let use_statements = wrapped_in_mod.use_statements_for_uniquely_named_types();
// then
let expected_use_statements = quote! {pub use a_mod::SomeType;};
assert_eq!(
use_statements.to_string(),
expected_use_statements.to_string()
);
}
#[test]
fn merging_code_will_merge_mods_as_well() {
// given
let common_struct_1 = given_some_struct_code("SomeStruct1")
.wrap_in_mod(given_type_path("common_mod::deeper_mod"));
let common_struct_2 =
given_some_struct_code("SomeStruct2").wrap_in_mod(given_type_path("common_mod"));
let top_level_struct = given_some_struct_code("TopLevelStruct");
let different_mod_struct =
given_some_struct_code("SomeStruct3").wrap_in_mod(given_type_path("different_mod"));
// when
let merged_code = common_struct_1
.merge(common_struct_2)
.merge(top_level_struct)
.merge(different_mod_struct);
// then
let prelude = quote! {
use ::core::{
clone::Clone,
convert::{Into, TryFrom, From},
iter::IntoIterator,
iter::Iterator,
marker::Sized,
panic,
};
use ::std::{string::ToString, format, vec, default::Default};
};
let expected_code = quote! {
struct TopLevelStruct;
#[allow(clippy::too_many_arguments)]
#[allow(clippy::disallowed_names)]
#[no_implicit_prelude]
pub mod common_mod {
#prelude
struct SomeStruct2;
#[allow(clippy::too_many_arguments)]
#[allow(clippy::disallowed_names)]
#[no_implicit_prelude]
pub mod deeper_mod {
#prelude
struct SomeStruct1;
}
}
#[allow(clippy::too_many_arguments)]
#[allow(clippy::disallowed_names)]
#[no_implicit_prelude]
pub mod different_mod {
#prelude
struct SomeStruct3;
}
};
let code = merged_code.code();
assert_eq!(code.to_string(), expected_code.to_string());
let use_statements = merged_code.use_statements_for_uniquely_named_types();
let expected_use_statements = quote! {
pub use common_mod::deeper_mod::SomeStruct1;
pub use common_mod::SomeStruct2;
pub use different_mod::SomeStruct3;
};
assert_eq!(
use_statements.to_string(),
expected_use_statements.to_string()
);
}
#[test]
fn use_statement_not_generated_for_top_level_type() {
let usable_types = ["TopLevelImport", "something::Deeper"]
.map(given_type_path)
.into_iter()
.collect();
let code = GeneratedCode::new(Default::default(), usable_types, false);
let use_statements = code.use_statements_for_uniquely_named_types();
let expected_use_statements = quote! {
pub use something::Deeper;
};
assert_eq!(
use_statements.to_string(),
expected_use_statements.to_string()
);
}
#[test]
fn use_statements_only_for_uniquely_named_types() {
// given
let not_unique_struct =
given_some_struct_code("NotUnique").wrap_in_mod(TypePath::new("another_mod").unwrap());
let generated_code = GeneratedCode::new(
Default::default(),
HashSet::from([
given_type_path("some_mod::Unique"),
given_type_path("even_though::the_duplicate_is::in_another_mod::NotUnique"),
]),
false,
)
.merge(not_unique_struct);
// when
let use_statements = generated_code.use_statements_for_uniquely_named_types();
// then
let expected_use_statements = quote! {
pub use some_mod::Unique;
};
assert_eq!(
use_statements.to_string(),
expected_use_statements.to_string()
);
}
fn given_some_struct_code(struct_name: &str) -> GeneratedCode {
let struct_ident = ident(struct_name);
GeneratedCode::new(
quote! {struct #struct_ident;},
HashSet::from([given_type_path(struct_name)]),
false,
)
}
fn given_type_path(path: &str) -> TypePath {
TypePath::new(path).expect("hand crafted, should be valid")
}
}
| rust | Apache-2.0 | 865e00c295de8b4a0a1ef7ac926c3c8266d5151b | 2026-01-04T15:31:59.450823Z | false |
FuelLabs/fuels-rs | https://github.com/FuelLabs/fuels-rs/blob/865e00c295de8b4a0a1ef7ac926c3c8266d5151b/packages/fuels-code-gen/src/program_bindings/abigen.rs | packages/fuels-code-gen/src/program_bindings/abigen.rs | use std::{collections::HashSet, path::PathBuf};
pub use abigen_target::{Abi, AbigenTarget, ProgramType};
use fuel_abi_types::abi::full_program::{FullLoggedType, FullTypeDeclaration};
use inflector::Inflector;
use itertools::Itertools;
use proc_macro2::TokenStream;
use quote::quote;
use regex::Regex;
use crate::{
error::Result,
program_bindings::{
abigen::bindings::generate_bindings, custom_types::generate_types,
generated_code::GeneratedCode,
},
utils::ident,
};
mod abigen_target;
mod bindings;
mod configurables;
mod logs;
pub struct Abigen;
impl Abigen {
/// Generate code which can be used to interact with the underlying
/// contract, script or predicate in a type-safe manner.
///
/// # Arguments
///
/// * `targets`: `AbigenTargets` detailing which ABI to generate bindings
/// for, and of what nature (Contract, Script or Predicate).
/// * `no_std`: don't use the Rust std library.
pub fn generate(targets: Vec<AbigenTarget>, no_std: bool) -> Result<TokenStream> {
let generated_code = Self::generate_code(no_std, targets)?;
let use_statements = generated_code.use_statements_for_uniquely_named_types();
let code = if no_std {
Self::wasm_paths_hotfix(&generated_code.code())
} else {
generated_code.code()
};
Ok(quote! {
#code
#use_statements
})
}
fn wasm_paths_hotfix(code: &TokenStream) -> TokenStream {
[
(r"::\s*std\s*::\s*string", "::alloc::string"),
(r"::\s*std\s*::\s*format", "::alloc::format"),
(r"::\s*std\s*::\s*vec", "::alloc::vec"),
(r"::\s*std\s*::\s*boxed", "::alloc::boxed"),
]
.map(|(reg_expr_str, substitute)| (Regex::new(reg_expr_str).unwrap(), substitute))
.into_iter()
.fold(code.to_string(), |code, (regex, wasm_include)| {
regex.replace_all(&code, wasm_include).to_string()
})
.parse()
.expect("Wasm hotfix failed!")
}
fn generate_code(no_std: bool, parsed_targets: Vec<AbigenTarget>) -> Result<GeneratedCode> {
let custom_types = Self::filter_custom_types(&parsed_targets);
let shared_types = Self::filter_shared_types(custom_types);
let logged_types = parsed_targets
.iter()
.flat_map(|abi| abi.source.abi.logged_types.clone())
.collect_vec();
let bindings = Self::generate_all_bindings(parsed_targets, no_std, &shared_types)?;
let shared_types = Self::generate_shared_types(shared_types, &logged_types, no_std)?;
let mod_name = ident("abigen_bindings");
Ok(shared_types.merge(bindings).wrap_in_mod(mod_name))
}
fn generate_all_bindings(
targets: Vec<AbigenTarget>,
no_std: bool,
shared_types: &HashSet<FullTypeDeclaration>,
) -> Result<GeneratedCode> {
targets
.into_iter()
.map(|target| Self::generate_binding(target, no_std, shared_types))
.fold_ok(GeneratedCode::default(), |acc, generated_code| {
acc.merge(generated_code)
})
}
fn generate_binding(
target: AbigenTarget,
no_std: bool,
shared_types: &HashSet<FullTypeDeclaration>,
) -> Result<GeneratedCode> {
let mod_name = ident(&format!("{}_mod", &target.name.to_snake_case()));
let recompile_trigger =
Self::generate_macro_recompile_trigger(target.source.path.as_ref(), no_std);
let types = generate_types(
&target.source.abi.types,
shared_types,
&target.source.abi.logged_types,
no_std,
)?;
let bindings = generate_bindings(target, no_std)?;
Ok(recompile_trigger
.merge(types)
.merge(bindings)
.wrap_in_mod(mod_name))
}
/// Any changes to the file pointed to by `path` will cause the reevaluation of the current
/// procedural macro. This is a hack until <https://github.com/rust-lang/rust/issues/99515>
/// lands.
fn generate_macro_recompile_trigger(path: Option<&PathBuf>, no_std: bool) -> GeneratedCode {
let code = path
.as_ref()
.map(|path| {
let stringified_path = path.display().to_string();
quote! {
const _: &[u8] = include_bytes!(#stringified_path);
}
})
.unwrap_or_default();
GeneratedCode::new(code, Default::default(), no_std)
}
fn generate_shared_types(
shared_types: HashSet<FullTypeDeclaration>,
logged_types: &Vec<FullLoggedType>,
no_std: bool,
) -> Result<GeneratedCode> {
let types = generate_types(&shared_types, &HashSet::default(), logged_types, no_std)?;
if types.is_empty() {
Ok(Default::default())
} else {
let mod_name = ident("shared_types");
Ok(types.wrap_in_mod(mod_name))
}
}
fn filter_custom_types(
all_types: &[AbigenTarget],
) -> impl Iterator<Item = &FullTypeDeclaration> {
all_types
.iter()
.flat_map(|target| &target.source.abi.types)
.filter(|ttype| ttype.is_custom_type())
}
/// A type is considered "shared" if it appears at least twice in
/// `all_custom_types`.
///
/// # Arguments
///
/// * `all_custom_types`: types from all ABIs whose bindings are being
/// generated.
fn filter_shared_types<'a>(
all_custom_types: impl IntoIterator<Item = &'a FullTypeDeclaration>,
) -> HashSet<FullTypeDeclaration> {
all_custom_types.into_iter().duplicates().cloned().collect()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn correctly_determines_shared_types() {
let types = ["type_0", "type_1", "type_0"].map(|type_field| FullTypeDeclaration {
type_field: type_field.to_string(),
components: vec![],
type_parameters: vec![],
alias_of: None,
});
let shared_types = Abigen::filter_shared_types(&types);
assert_eq!(shared_types, HashSet::from([types[0].clone()]))
}
}
| rust | Apache-2.0 | 865e00c295de8b4a0a1ef7ac926c3c8266d5151b | 2026-01-04T15:31:59.450823Z | false |
FuelLabs/fuels-rs | https://github.com/FuelLabs/fuels-rs/blob/865e00c295de8b4a0a1ef7ac926c3c8266d5151b/packages/fuels-code-gen/src/program_bindings/utils.rs | packages/fuels-code-gen/src/program_bindings/utils.rs | use std::collections::{HashMap, HashSet};
use fuel_abi_types::abi::full_program::FullTypeApplication;
use inflector::Inflector;
use itertools::Itertools;
use proc_macro2::{Ident, TokenStream};
use quote::quote;
use crate::{
error::Result,
program_bindings::resolved_type::{GenericType, ResolvedType, TypeResolver},
utils::{self, TypePath, safe_ident},
};
#[derive(Debug)]
pub(crate) struct Component {
pub(crate) ident: Ident,
pub(crate) resolved_type: ResolvedType,
pub(crate) error_message: Option<String>,
}
#[derive(Debug)]
pub(crate) struct Components {
components: Vec<Component>,
}
impl Components {
pub fn new(
type_applications: &[FullTypeApplication],
snake_case: bool,
parent_module: TypePath,
) -> Result<Self> {
let type_resolver = TypeResolver::new(parent_module);
let components = type_applications
.iter()
.map(|type_application| {
let name = if snake_case {
type_application.name.to_snake_case()
} else {
type_application.name.to_owned()
};
let ident = safe_ident(&name);
let resolved_type = type_resolver.resolve(type_application)?;
let error_message = type_application.error_message.clone();
Result::Ok(Component {
ident,
resolved_type,
error_message,
})
})
.collect::<Result<Vec<_>>>()?;
Ok(Self { components })
}
pub fn has_error_messages(&self) -> bool {
self.components
.iter()
.all(|component| component.error_message.is_some())
}
pub fn iter(&self) -> impl Iterator<Item = &Component> {
self.components.iter()
}
pub fn is_empty(&self) -> bool {
self.components.is_empty()
}
pub fn as_enum_variants(&self) -> impl Iterator<Item = TokenStream> + '_ {
self.components.iter().map(
|Component {
ident,
resolved_type,
..
}| {
if let ResolvedType::Unit = resolved_type {
quote! {#ident}
} else {
quote! {#ident(#resolved_type)}
}
},
)
}
pub fn generate_parameters_for_unused_generics(
&self,
declared_generics: &[Ident],
) -> (Vec<Ident>, Vec<TokenStream>) {
self.unused_named_generics(declared_generics)
.enumerate()
.map(|(index, generic)| {
let ident = utils::ident(&format!("_unused_generic_{index}"));
let ty = quote! {::core::marker::PhantomData<#generic>};
(ident, ty)
})
.unzip()
}
pub fn generate_variant_for_unused_generics(
&self,
declared_generics: &[Ident],
) -> Option<TokenStream> {
let phantom_types = self
.unused_named_generics(declared_generics)
.map(|generic| {
quote! {::core::marker::PhantomData<#generic>}
})
.collect_vec();
(!phantom_types.is_empty()).then(|| {
quote! {
#[Ignore]
IgnoreMe(#(#phantom_types),*)
}
})
}
fn named_generics(&self) -> HashSet<Ident> {
self.components
.iter()
.flat_map(|Component { resolved_type, .. }| resolved_type.generics())
.filter_map(|generic_type| {
if let GenericType::Named(name) = generic_type {
Some(name)
} else {
None
}
})
.collect()
}
fn unused_named_generics<'a>(
&'a self,
declared_generics: &'a [Ident],
) -> impl Iterator<Item = &'a Ident> {
let used_generics = self.named_generics();
declared_generics
.iter()
.filter(move |generic| !used_generics.contains(generic))
}
}
pub(crate) fn tokenize_generics(generics: &[Ident]) -> (TokenStream, TokenStream) {
if generics.is_empty() {
return (Default::default(), Default::default());
}
(
quote! {<#(#generics,)*>},
quote! {<#(#generics: ::fuels::core::traits::Tokenizable + ::fuels::core::traits::Parameterize, )*>},
)
}
pub(crate) fn sdk_provided_custom_types_lookup() -> HashMap<TypePath, TypePath> {
[
("std::address::Address", "::fuels::types::Address"),
("std::asset_id::AssetId", "::fuels::types::AssetId"),
("std::b512::B512", "::fuels::types::B512"),
("std::bytes::Bytes", "::fuels::types::Bytes"),
("std::contract_id::ContractId", "::fuels::types::ContractId"),
("std::identity::Identity", "::fuels::types::Identity"),
("std::option::Option", "::core::option::Option"),
("std::result::Result", "::core::result::Result"),
("std::string::String", "::std::string::String"),
("std::vec::Vec", "::std::vec::Vec"),
(
"std::vm::evm::evm_address::EvmAddress",
"::fuels::types::EvmAddress",
),
]
.into_iter()
.map(|(original_type_path, provided_type_path)| {
let msg = "known at compile time to be correctly formed";
(
TypePath::new(original_type_path).expect(msg),
TypePath::new(provided_type_path).expect(msg),
)
})
.collect()
}
#[cfg(test)]
mod tests {
use fuel_abi_types::abi::full_program::FullTypeDeclaration;
use super::*;
#[test]
fn respects_snake_case_flag() -> Result<()> {
// given
let type_application = type_application_named("WasNotSnakeCased");
// when
let sut = Components::new(&[type_application], true, TypePath::default())?;
// then
assert_eq!(sut.iter().next().unwrap().ident, "was_not_snake_cased");
Ok(())
}
#[test]
fn avoids_collisions_with_reserved_keywords() -> Result<()> {
{
let type_application = type_application_named("if");
let sut = Components::new(&[type_application], false, TypePath::default())?;
assert_eq!(sut.iter().next().unwrap().ident, "if_");
}
{
let type_application = type_application_named("let");
let sut = Components::new(&[type_application], false, TypePath::default())?;
assert_eq!(sut.iter().next().unwrap().ident, "let_");
}
Ok(())
}
fn type_application_named(name: &str) -> FullTypeApplication {
FullTypeApplication {
name: name.to_string(),
type_decl: FullTypeDeclaration {
type_field: "u64".to_string(),
components: vec![],
type_parameters: vec![],
alias_of: None,
},
type_arguments: vec![],
error_message: None,
}
}
}
| rust | Apache-2.0 | 865e00c295de8b4a0a1ef7ac926c3c8266d5151b | 2026-01-04T15:31:59.450823Z | false |
FuelLabs/fuels-rs | https://github.com/FuelLabs/fuels-rs/blob/865e00c295de8b4a0a1ef7ac926c3c8266d5151b/packages/fuels-code-gen/src/program_bindings/resolved_type.rs | packages/fuels-code-gen/src/program_bindings/resolved_type.rs | use std::fmt::{Display, Formatter};
use fuel_abi_types::{
abi::full_program::FullTypeApplication,
utils::{self, extract_array_len, extract_generic_name, extract_str_len, has_tuple_format},
};
use proc_macro2::{Ident, TokenStream};
use quote::{ToTokens, quote};
use crate::{
error::{Result, error},
program_bindings::utils::sdk_provided_custom_types_lookup,
utils::TypePath,
};
#[derive(Debug, Clone, PartialEq)]
pub enum GenericType {
Named(Ident),
Constant(usize),
}
impl ToTokens for GenericType {
fn to_tokens(&self, tokens: &mut TokenStream) {
let stream = match self {
GenericType::Named(ident) => ident.to_token_stream(),
GenericType::Constant(constant) => constant.to_token_stream(),
};
tokens.extend(stream);
}
}
/// Represents a Rust type alongside its generic parameters. For when you want to reference an ABI
/// type in Rust code since [`ResolvedType`] can be converted into a [`TokenStream`] via
/// `resolved_type.to_token_stream()`.
#[derive(Debug, Clone)]
pub enum ResolvedType {
Unit,
Primitive(TypePath),
StructOrEnum {
path: TypePath,
generics: Vec<ResolvedType>,
},
Array(Box<ResolvedType>, usize),
Tuple(Vec<ResolvedType>),
Generic(GenericType),
}
impl ResolvedType {
pub fn generics(&self) -> Vec<GenericType> {
match self {
ResolvedType::StructOrEnum {
generics: elements, ..
}
| ResolvedType::Tuple(elements) => {
elements.iter().flat_map(|el| el.generics()).collect()
}
ResolvedType::Array(el, _) => el.generics(),
ResolvedType::Generic(inner) => vec![inner.clone()],
_ => vec![],
}
}
}
impl ToTokens for ResolvedType {
fn to_tokens(&self, tokens: &mut TokenStream) {
let tokenized = match self {
ResolvedType::Unit => quote! {()},
ResolvedType::Primitive(path) => path.into_token_stream(),
ResolvedType::StructOrEnum { path, generics } => {
if generics.is_empty() {
path.to_token_stream()
} else {
quote! { #path<#(#generics),*>}
}
}
ResolvedType::Array(el, count) => quote! { [#el; #count]},
ResolvedType::Tuple(elements) => {
// it is important to leave a trailing comma because a tuple with
// one element is written as (element,) not (element) which is
// resolved to just element
quote! { (#(#elements,)*) }
}
ResolvedType::Generic(generic_type) => generic_type.into_token_stream(),
};
tokens.extend(tokenized)
}
}
impl Display for ResolvedType {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.to_token_stream())
}
}
/// Used to resolve [`FullTypeApplication`]s into [`ResolvedType`]s
pub(crate) struct TypeResolver {
/// The mod in which the produced [`ResolvedType`]s are going to end up in.
current_mod: TypePath,
}
impl Default for TypeResolver {
fn default() -> Self {
TypeResolver::new(Default::default())
}
}
impl TypeResolver {
pub(crate) fn new(current_mod: TypePath) -> Self {
Self { current_mod }
}
pub(crate) fn resolve(&self, type_application: &FullTypeApplication) -> Result<ResolvedType> {
let resolvers = [
Self::try_as_primitive_type,
Self::try_as_bits256,
Self::try_as_generic,
Self::try_as_array,
Self::try_as_sized_ascii_string,
Self::try_as_ascii_string,
Self::try_as_tuple,
Self::try_as_raw_slice,
Self::try_as_custom_type,
];
for resolver in resolvers {
if let Some(resolved) = resolver(self, type_application)? {
return Ok(resolved);
}
}
let type_field = &type_application.type_decl.type_field;
Err(error!("could not resolve '{type_field}' to any known type"))
}
fn resolve_multiple(
&self,
type_applications: &[FullTypeApplication],
) -> Result<Vec<ResolvedType>> {
type_applications
.iter()
.map(|type_application| self.resolve(type_application))
.collect()
}
fn try_as_generic(
&self,
type_application: &FullTypeApplication,
) -> Result<Option<ResolvedType>> {
let Some(name) = extract_generic_name(&type_application.type_decl.type_field) else {
return Ok(None);
};
let ident = utils::safe_ident(&name);
Ok(Some(ResolvedType::Generic(GenericType::Named(ident))))
}
fn try_as_array(&self, type_application: &FullTypeApplication) -> Result<Option<ResolvedType>> {
let type_decl = &type_application.type_decl;
let Some(len) = extract_array_len(&type_decl.type_field) else {
return Ok(None);
};
let components = self.resolve_multiple(&type_decl.components)?;
let type_inside = match components.as_slice() {
[single_type] => single_type,
other => {
return Err(error!(
"array must have only one component. Actual components: {other:?}"
));
}
};
Ok(Some(ResolvedType::Array(
Box::new(type_inside.clone()),
len,
)))
}
fn try_as_sized_ascii_string(
&self,
type_application: &FullTypeApplication,
) -> Result<Option<ResolvedType>> {
let Some(len) = extract_str_len(&type_application.type_decl.type_field) else {
return Ok(None);
};
let path =
TypePath::new("::fuels::types::SizedAsciiString").expect("this is a valid TypePath");
Ok(Some(ResolvedType::StructOrEnum {
path,
generics: vec![ResolvedType::Generic(GenericType::Constant(len))],
}))
}
fn try_as_ascii_string(
&self,
type_application: &FullTypeApplication,
) -> Result<Option<ResolvedType>> {
let maybe_resolved = (type_application.type_decl.type_field == "str").then(|| {
let path =
TypePath::new("::fuels::types::AsciiString").expect("this is a valid TypePath");
ResolvedType::StructOrEnum {
path,
generics: vec![],
}
});
Ok(maybe_resolved)
}
fn try_as_tuple(&self, type_application: &FullTypeApplication) -> Result<Option<ResolvedType>> {
let type_decl = &type_application.type_decl;
if !has_tuple_format(&type_decl.type_field) {
return Ok(None);
}
let inner_types = self.resolve_multiple(&type_decl.components)?;
Ok(Some(ResolvedType::Tuple(inner_types)))
}
fn try_as_primitive_type(
&self,
type_decl: &FullTypeApplication,
) -> Result<Option<ResolvedType>> {
let type_field = &type_decl.type_decl.type_field;
let maybe_resolved = match type_field.as_str() {
"()" => Some(ResolvedType::Unit),
"bool" | "u8" | "u16" | "u32" | "u64" => {
let path = format!("::core::primitive::{type_field}");
let type_path = TypePath::new(path).expect("to be a valid path");
Some(ResolvedType::Primitive(type_path))
}
"struct std::u128::U128" | "struct U128" => {
let u128_path = TypePath::new("::core::primitive::u128").expect("is correct");
Some(ResolvedType::Primitive(u128_path))
}
"u256" => {
let u256_path = TypePath::new("::fuels::types::U256").expect("is correct");
Some(ResolvedType::Primitive(u256_path))
}
_ => None,
};
Ok(maybe_resolved)
}
fn try_as_bits256(
&self,
type_application: &FullTypeApplication,
) -> Result<Option<ResolvedType>> {
if type_application.type_decl.type_field != "b256" {
return Ok(None);
}
let path = TypePath::new("::fuels::types::Bits256").expect("to be valid");
Ok(Some(ResolvedType::StructOrEnum {
path,
generics: vec![],
}))
}
fn try_as_raw_slice(
&self,
type_application: &FullTypeApplication,
) -> Result<Option<ResolvedType>> {
if type_application.type_decl.type_field != "raw untyped slice" {
return Ok(None);
}
let path = TypePath::new("::fuels::types::RawSlice").expect("this is a valid TypePath");
Ok(Some(ResolvedType::StructOrEnum {
path,
generics: vec![],
}))
}
fn try_as_custom_type(
&self,
type_application: &FullTypeApplication,
) -> Result<Option<ResolvedType>> {
let type_decl = &type_application.type_decl;
if !type_decl.is_custom_type() {
return Ok(None);
}
let original_path = type_decl.custom_type_path()?;
let used_path = sdk_provided_custom_types_lookup()
.get(&original_path)
.cloned()
.unwrap_or_else(|| original_path.relative_path_from(&self.current_mod));
let generics = self.resolve_multiple(&type_application.type_arguments)?;
Ok(Some(ResolvedType::StructOrEnum {
path: used_path,
generics,
}))
}
}
#[cfg(test)]
mod tests {
use std::{collections::HashMap, str::FromStr};
use fuel_abi_types::{
abi::{
full_program::FullTypeDeclaration,
unified_program::{UnifiedTypeApplication, UnifiedTypeDeclaration},
},
utils::ident,
};
use super::*;
#[test]
fn correctly_extracts_used_generics() {
let resolved_type = ResolvedType::StructOrEnum {
path: Default::default(),
generics: vec![
ResolvedType::Tuple(vec![ResolvedType::Array(
Box::new(ResolvedType::StructOrEnum {
path: Default::default(),
generics: vec![
ResolvedType::Generic(GenericType::Named(ident("A"))),
ResolvedType::Generic(GenericType::Constant(10)),
],
}),
2,
)]),
ResolvedType::Generic(GenericType::Named(ident("B"))),
],
};
let generics = resolved_type.generics();
assert_eq!(
generics,
vec![
GenericType::Named(ident("A")),
GenericType::Constant(10),
GenericType::Named(ident("B"))
]
)
}
fn test_resolve_first_type(
expected: &str,
type_declarations: &[UnifiedTypeDeclaration],
) -> Result<()> {
let types = type_declarations
.iter()
.map(|td| (td.type_id, td.clone()))
.collect::<HashMap<_, _>>();
let type_application = UnifiedTypeApplication {
type_id: type_declarations[0].type_id,
..Default::default()
};
let application = FullTypeApplication::from_counterpart(&type_application, &types);
let resolved_type = TypeResolver::default()
.resolve(&application)
.map_err(|e| e.combine(error!("failed to resolve {:?}", type_application)))?;
let actual = resolved_type.to_token_stream().to_string();
let expected = TokenStream::from_str(expected).unwrap().to_string();
assert_eq!(actual, expected);
Ok(())
}
fn test_resolve_primitive_type(type_field: &str, expected: &str) -> Result<()> {
test_resolve_first_type(
expected,
&[UnifiedTypeDeclaration {
type_id: 0,
type_field: type_field.to_string(),
..Default::default()
}],
)
}
#[test]
fn test_resolve_u8() -> Result<()> {
test_resolve_primitive_type("u8", "::core::primitive::u8")
}
#[test]
fn test_resolve_u16() -> Result<()> {
test_resolve_primitive_type("u16", "::core::primitive::u16")
}
#[test]
fn test_resolve_u32() -> Result<()> {
test_resolve_primitive_type("u32", "::core::primitive::u32")
}
#[test]
fn test_resolve_u64() -> Result<()> {
test_resolve_primitive_type("u64", "::core::primitive::u64")
}
#[test]
fn test_resolve_bool() -> Result<()> {
test_resolve_primitive_type("bool", "::core::primitive::bool")
}
#[test]
fn test_resolve_b256() -> Result<()> {
test_resolve_primitive_type("b256", "::fuels::types::Bits256")
}
#[test]
fn test_resolve_unit() -> Result<()> {
test_resolve_primitive_type("()", "()")
}
#[test]
fn test_resolve_array() -> Result<()> {
test_resolve_first_type(
"[::core::primitive::u8 ; 3usize]",
&[
UnifiedTypeDeclaration {
type_id: 0,
type_field: "[u8; 3]".to_string(),
components: Some(vec![UnifiedTypeApplication {
type_id: 1,
..Default::default()
}]),
..Default::default()
},
UnifiedTypeDeclaration {
type_id: 1,
type_field: "u8".to_string(),
..Default::default()
},
],
)
}
#[test]
fn test_resolve_vector() -> Result<()> {
test_resolve_first_type(
":: std :: vec :: Vec",
&[
UnifiedTypeDeclaration {
type_id: 0,
type_field: "struct std::vec::Vec".to_string(),
components: Some(vec![
UnifiedTypeApplication {
name: "buf".to_string(),
type_id: 2,
type_arguments: Some(vec![UnifiedTypeApplication {
type_id: 1,
..Default::default()
}]),
error_message: None,
},
UnifiedTypeApplication {
name: "len".to_string(),
type_id: 3,
..Default::default()
},
]),
type_parameters: Some(vec![1]),
alias_of: None,
},
UnifiedTypeDeclaration {
type_id: 1,
type_field: "generic T".to_string(),
..Default::default()
},
UnifiedTypeDeclaration {
type_id: 2,
type_field: "raw untyped ptr".to_string(),
..Default::default()
},
UnifiedTypeDeclaration {
type_id: 3,
type_field: "struct std::vec::RawVec".to_string(),
components: Some(vec![
UnifiedTypeApplication {
name: "ptr".to_string(),
type_id: 2,
..Default::default()
},
UnifiedTypeApplication {
name: "cap".to_string(),
type_id: 4,
..Default::default()
},
]),
type_parameters: Some(vec![1]),
alias_of: None,
},
UnifiedTypeDeclaration {
type_id: 4,
type_field: "u64".to_string(),
..Default::default()
},
UnifiedTypeDeclaration {
type_id: 5,
type_field: "u8".to_string(),
..Default::default()
},
],
)
}
#[test]
fn test_resolve_bytes() -> Result<()> {
test_resolve_first_type(
":: fuels :: types :: Bytes",
&[
UnifiedTypeDeclaration {
type_id: 0,
type_field: "struct String".to_string(),
components: Some(vec![UnifiedTypeApplication {
name: "bytes".to_string(),
type_id: 1,
..Default::default()
}]),
..Default::default()
},
UnifiedTypeDeclaration {
type_id: 0,
type_field: "struct std::bytes::Bytes".to_string(),
components: Some(vec![
UnifiedTypeApplication {
name: "buf".to_string(),
type_id: 1,
..Default::default()
},
UnifiedTypeApplication {
name: "len".to_string(),
type_id: 3,
..Default::default()
},
]),
..Default::default()
},
UnifiedTypeDeclaration {
type_id: 1,
type_field: "struct std::bytes::RawBytes".to_string(),
components: Some(vec![
UnifiedTypeApplication {
name: "ptr".to_string(),
type_id: 2,
..Default::default()
},
UnifiedTypeApplication {
name: "cap".to_string(),
type_id: 3,
..Default::default()
},
]),
..Default::default()
},
UnifiedTypeDeclaration {
type_id: 2,
type_field: "raw untyped ptr".to_string(),
..Default::default()
},
UnifiedTypeDeclaration {
type_id: 3,
type_field: "u64".to_string(),
..Default::default()
},
],
)
}
#[test]
fn test_resolve_std_string() -> Result<()> {
test_resolve_first_type(
":: std :: string :: String",
&[
UnifiedTypeDeclaration {
type_id: 0,
type_field: "struct std::string::String".to_string(),
components: Some(vec![UnifiedTypeApplication {
name: "bytes".to_string(),
type_id: 1,
..Default::default()
}]),
..Default::default()
},
UnifiedTypeDeclaration {
type_id: 1,
type_field: "struct std::bytes::Bytes".to_string(),
components: Some(vec![
UnifiedTypeApplication {
name: "buf".to_string(),
type_id: 2,
..Default::default()
},
UnifiedTypeApplication {
name: "len".to_string(),
type_id: 4,
..Default::default()
},
]),
..Default::default()
},
UnifiedTypeDeclaration {
type_id: 2,
type_field: "struct std::bytes::RawBytes".to_string(),
components: Some(vec![
UnifiedTypeApplication {
name: "ptr".to_string(),
type_id: 3,
..Default::default()
},
UnifiedTypeApplication {
name: "cap".to_string(),
type_id: 4,
..Default::default()
},
]),
..Default::default()
},
UnifiedTypeDeclaration {
type_id: 3,
type_field: "raw untyped ptr".to_string(),
..Default::default()
},
UnifiedTypeDeclaration {
type_id: 4,
type_field: "u64".to_string(),
..Default::default()
},
],
)
}
#[test]
fn test_resolve_static_str() -> Result<()> {
test_resolve_primitive_type("str[3]", ":: fuels :: types :: SizedAsciiString < 3usize >")
}
#[test]
fn test_resolve_struct() -> Result<()> {
test_resolve_first_type(
"self :: SomeStruct",
&[
UnifiedTypeDeclaration {
type_id: 0,
type_field: "struct SomeStruct".to_string(),
components: Some(vec![
UnifiedTypeApplication {
name: "foo".to_string(),
type_id: 1,
..Default::default()
},
UnifiedTypeApplication {
name: "bar".to_string(),
type_id: 2,
..Default::default()
},
]),
type_parameters: Some(vec![1]),
alias_of: None,
},
UnifiedTypeDeclaration {
type_id: 1,
type_field: "generic T".to_string(),
..Default::default()
},
UnifiedTypeDeclaration {
type_id: 2,
type_field: "u8".to_string(),
..Default::default()
},
],
)
}
#[test]
fn test_resolve_enum() -> Result<()> {
test_resolve_first_type(
"self :: SomeEnum",
&[
UnifiedTypeDeclaration {
type_id: 0,
type_field: "enum SomeEnum".to_string(),
components: Some(vec![
UnifiedTypeApplication {
name: "foo".to_string(),
type_id: 1,
..Default::default()
},
UnifiedTypeApplication {
name: "bar".to_string(),
type_id: 2,
..Default::default()
},
]),
type_parameters: Some(vec![1]),
alias_of: None,
},
UnifiedTypeDeclaration {
type_id: 1,
type_field: "generic T".to_string(),
..Default::default()
},
UnifiedTypeDeclaration {
type_id: 2,
type_field: "u8".to_string(),
..Default::default()
},
],
)
}
#[test]
fn test_resolve_tuple() -> Result<()> {
test_resolve_first_type(
"(::core::primitive::u8, ::core::primitive::u16, ::core::primitive::bool, T,)",
&[
UnifiedTypeDeclaration {
type_id: 0,
type_field: "(u8, u16, bool, T)".to_string(),
components: Some(vec![
UnifiedTypeApplication {
type_id: 1,
..Default::default()
},
UnifiedTypeApplication {
type_id: 2,
..Default::default()
},
UnifiedTypeApplication {
type_id: 3,
..Default::default()
},
UnifiedTypeApplication {
type_id: 4,
..Default::default()
},
]),
type_parameters: Some(vec![4]),
alias_of: None,
},
UnifiedTypeDeclaration {
type_id: 1,
type_field: "u8".to_string(),
..Default::default()
},
UnifiedTypeDeclaration {
type_id: 2,
type_field: "u16".to_string(),
..Default::default()
},
UnifiedTypeDeclaration {
type_id: 3,
type_field: "bool".to_string(),
..Default::default()
},
UnifiedTypeDeclaration {
type_id: 4,
type_field: "generic T".to_string(),
..Default::default()
},
],
)
}
#[test]
fn custom_types_uses_correct_path_for_sdk_provided_types() {
let resolver = TypeResolver::default();
for (type_path, expected_path) in sdk_provided_custom_types_lookup() {
// given
let type_application = given_fn_arg_of_custom_type(&type_path);
// when
let resolved_type = resolver.resolve(&type_application).unwrap();
// then
let expected_type_name = expected_path.into_token_stream();
assert_eq!(
resolved_type.to_token_stream().to_string(),
expected_type_name.to_string()
);
}
}
fn given_fn_arg_of_custom_type(type_path: &TypePath) -> FullTypeApplication {
FullTypeApplication {
name: "some_arg".to_string(),
type_decl: FullTypeDeclaration {
type_field: format!("struct {type_path}"),
components: vec![],
type_parameters: vec![],
alias_of: None,
},
type_arguments: vec![],
error_message: None,
}
}
}
| rust | Apache-2.0 | 865e00c295de8b4a0a1ef7ac926c3c8266d5151b | 2026-01-04T15:31:59.450823Z | false |
FuelLabs/fuels-rs | https://github.com/FuelLabs/fuels-rs/blob/865e00c295de8b4a0a1ef7ac926c3c8266d5151b/packages/fuels-code-gen/src/program_bindings/custom_types.rs | packages/fuels-code-gen/src/program_bindings/custom_types.rs | use std::collections::{HashMap, HashSet};
use fuel_abi_types::abi::full_program::{FullLoggedType, FullTypeDeclaration};
use itertools::Itertools;
use quote::quote;
use crate::{
error::Result,
program_bindings::{
custom_types::{enums::expand_custom_enum, structs::expand_custom_struct},
generated_code::GeneratedCode,
utils::sdk_provided_custom_types_lookup,
},
utils::TypePath,
};
mod enums;
mod structs;
pub(crate) mod utils;
/// Generates Rust code for each type inside `types` if:
/// * the type is not present inside `shared_types`, and
/// * if it should be generated (see: [`should_skip_codegen`], and
/// * if it is a struct or an enum.
///
///
/// # Arguments
///
/// * `types`: Types you wish to generate Rust code for.
/// * `shared_types`: Types that are shared between multiple
/// contracts/scripts/predicates and thus generated elsewhere.
pub(crate) fn generate_types<'a>(
types: impl IntoIterator<Item = &'a FullTypeDeclaration>,
shared_types: &HashSet<FullTypeDeclaration>,
logged_types: impl IntoIterator<Item = &'a FullLoggedType>,
no_std: bool,
) -> Result<GeneratedCode> {
let log_ids: HashMap<_, _> = logged_types
.into_iter()
.map(|l| (l.application.type_decl.type_field.clone(), l.log_id.clone()))
.collect();
types
.into_iter()
.filter(|ttype| !should_skip_codegen(ttype))
.map(|ttype: &FullTypeDeclaration| {
let log_id = log_ids.get(&ttype.type_field);
if shared_types.contains(ttype) {
reexport_the_shared_type(ttype, no_std)
} else if ttype.is_struct_type() {
expand_custom_struct(ttype, no_std, log_id)
} else {
expand_custom_enum(ttype, no_std, log_id)
}
})
.fold_ok(GeneratedCode::default(), |acc, generated_code| {
acc.merge(generated_code)
})
}
/// Instead of generating bindings for `ttype` this fn will just generate a `pub use` pointing to
/// the already generated equivalent shared type.
fn reexport_the_shared_type(ttype: &FullTypeDeclaration, no_std: bool) -> Result<GeneratedCode> {
// e.g. some_library::another_mod::SomeStruct
let type_path = ttype
.custom_type_path()
.expect("This must be a custom type due to the previous filter step");
let type_mod = type_path.parent();
let from_top_lvl_to_shared_types =
TypePath::new("super::shared_types").expect("This is known to be a valid TypePath");
let top_lvl_mod = TypePath::default();
let from_current_mod_to_top_level = top_lvl_mod.relative_path_from(&type_mod);
let path = from_current_mod_to_top_level
.append(from_top_lvl_to_shared_types)
.append(type_path);
// e.g. pub use super::super::super::shared_types::some_library::another_mod::SomeStruct;
let the_reexport = quote! {pub use #path;};
Ok(GeneratedCode::new(the_reexport, Default::default(), no_std).wrap_in_mod(type_mod))
}
// Checks whether the given type should not have code generated for it. This
// is mainly because the corresponding type in Rust already exists --
// e.g. the contract's Vec type is mapped to std::vec::Vec from the Rust
// stdlib, ContractId is a custom type implemented by fuels-rs, etc.
// Others like 'std::vec::RawVec' are skipped because they are
// implementation details of the contract's Vec type and are not directly
// used in the SDK.
pub fn should_skip_codegen(type_decl: &FullTypeDeclaration) -> bool {
if !type_decl.is_custom_type() {
return true;
}
let type_path = type_decl.custom_type_path().unwrap();
is_type_sdk_provided(&type_path) || is_type_unused(&type_path)
}
fn is_type_sdk_provided(type_path: &TypePath) -> bool {
sdk_provided_custom_types_lookup().contains_key(type_path)
}
fn is_type_unused(type_path: &TypePath) -> bool {
let msg = "Known to be correct";
[
TypePath::new("std::vec::RawVec").expect(msg),
TypePath::new("std::bytes::RawBytes").expect(msg),
]
.contains(type_path)
}
// Doing string -> TokenStream -> string isn't pretty but gives us the opportunity to
// have a better understanding of the generated code so we consider it ok.
// To generate the expected examples, output of the functions were taken
// with code @9ca376, and formatted in-IDE using rustfmt. It should be noted that
// rustfmt added an extra `,` after the last struct/enum field, which is not added
// by the `expand_custom_*` functions, and so was removed from the expected string.
// TODO(iqdecay): append extra `,` to last enum/struct field so it is aligned with rustfmt
#[cfg(test)]
mod tests {
use std::collections::HashMap;
use fuel_abi_types::abi::unified_program::{UnifiedTypeApplication, UnifiedTypeDeclaration};
use pretty_assertions::assert_eq;
use quote::quote;
use super::*;
#[test]
fn test_expand_custom_enum() -> Result<()> {
let p = UnifiedTypeDeclaration {
type_id: 0,
type_field: String::from("enum MatchaTea"),
components: Some(vec![
UnifiedTypeApplication {
name: String::from("LongIsland"),
type_id: 1,
..Default::default()
},
UnifiedTypeApplication {
name: String::from("MoscowMule"),
type_id: 2,
..Default::default()
},
]),
..Default::default()
};
let types = [
(0, p.clone()),
(
1,
UnifiedTypeDeclaration {
type_id: 1,
type_field: String::from("u64"),
..Default::default()
},
),
(
2,
UnifiedTypeDeclaration {
type_id: 2,
type_field: String::from("bool"),
..Default::default()
},
),
]
.into_iter()
.collect::<HashMap<_, _>>();
let actual = expand_custom_enum(
&FullTypeDeclaration::from_counterpart(&p, &types),
false,
None,
)?;
let expected = quote! {
#[allow(clippy::enum_variant_names)]
#[derive(
Clone,
Debug,
Eq,
PartialEq,
::fuels::macros::Parameterize,
::fuels::macros::Tokenizable,
::fuels::macros::TryFrom,
)]
pub enum MatchaTea {
LongIsland(::core::primitive::u64),
MoscowMule(::core::primitive::bool),
}
};
assert_eq!(actual.code().to_string(), expected.to_string());
Ok(())
}
#[test]
fn test_enum_with_no_variants_cannot_be_constructed() -> Result<()> {
let p = UnifiedTypeDeclaration {
type_id: 0,
type_field: "enum SomeEmptyEnum".to_string(),
components: Some(vec![]),
..Default::default()
};
let types = [(0, p.clone())].into_iter().collect::<HashMap<_, _>>();
expand_custom_enum(
&FullTypeDeclaration::from_counterpart(&p, &types),
false,
None,
)
.expect_err("Was able to construct an enum without variants");
Ok(())
}
#[test]
fn test_expand_struct_inside_enum() -> Result<()> {
let inner_struct = UnifiedTypeApplication {
name: String::from("Infrastructure"),
type_id: 1,
..Default::default()
};
let enum_components = vec![
inner_struct,
UnifiedTypeApplication {
name: "Service".to_string(),
type_id: 2,
..Default::default()
},
];
let p = UnifiedTypeDeclaration {
type_id: 0,
type_field: String::from("enum Amsterdam"),
components: Some(enum_components),
..Default::default()
};
let types = [
(0, p.clone()),
(
1,
UnifiedTypeDeclaration {
type_id: 1,
type_field: String::from("struct Building"),
components: Some(vec![]),
..Default::default()
},
),
(
2,
UnifiedTypeDeclaration {
type_id: 2,
type_field: String::from("u32"),
..Default::default()
},
),
]
.into_iter()
.collect::<HashMap<_, _>>();
let actual = expand_custom_enum(
&FullTypeDeclaration::from_counterpart(&p, &types),
false,
None,
)?;
let expected = quote! {
#[allow(clippy::enum_variant_names)]
#[derive(
Clone,
Debug,
Eq,
PartialEq,
::fuels::macros::Parameterize,
::fuels::macros::Tokenizable,
::fuels::macros::TryFrom,
)]
pub enum Amsterdam {
Infrastructure(self::Building),
Service(::core::primitive::u32),
}
};
assert_eq!(actual.code().to_string(), expected.to_string());
Ok(())
}
#[test]
fn test_expand_array_inside_enum() -> Result<()> {
let enum_components = vec![UnifiedTypeApplication {
name: "SomeArr".to_string(),
type_id: 1,
..Default::default()
}];
let p = UnifiedTypeDeclaration {
type_id: 0,
type_field: String::from("enum SomeEnum"),
components: Some(enum_components),
..Default::default()
};
let types = [
(0, p.clone()),
(
1,
UnifiedTypeDeclaration {
type_id: 1,
type_field: "[u64; 7]".to_string(),
components: Some(vec![UnifiedTypeApplication {
type_id: 2,
..Default::default()
}]),
..Default::default()
},
),
(
2,
UnifiedTypeDeclaration {
type_id: 2,
type_field: "u64".to_string(),
..Default::default()
},
),
]
.into_iter()
.collect::<HashMap<_, _>>();
let actual = expand_custom_enum(
&FullTypeDeclaration::from_counterpart(&p, &types),
false,
None,
)?;
let expected = quote! {
#[allow(clippy::enum_variant_names)]
#[derive(
Clone,
Debug,
Eq,
PartialEq,
::fuels::macros::Parameterize,
::fuels::macros::Tokenizable,
::fuels::macros::TryFrom,
)]
pub enum SomeEnum {
SomeArr([::core::primitive::u64; 7usize]),
}
};
assert_eq!(actual.code().to_string(), expected.to_string());
Ok(())
}
#[test]
fn test_expand_custom_enum_with_enum() -> Result<()> {
let p = UnifiedTypeDeclaration {
type_id: 3,
type_field: String::from("enum EnumLevel3"),
components: Some(vec![UnifiedTypeApplication {
name: String::from("El2"),
type_id: 2,
..Default::default()
}]),
..Default::default()
};
let types = [
(3, p.clone()),
(
2,
UnifiedTypeDeclaration {
type_id: 2,
type_field: String::from("enum EnumLevel2"),
components: Some(vec![UnifiedTypeApplication {
name: String::from("El1"),
type_id: 1,
..Default::default()
}]),
..Default::default()
},
),
(
1,
UnifiedTypeDeclaration {
type_id: 1,
type_field: String::from("enum EnumLevel1"),
components: Some(vec![UnifiedTypeApplication {
name: String::from("Num"),
type_id: 0,
..Default::default()
}]),
..Default::default()
},
),
(
0,
UnifiedTypeDeclaration {
type_id: 0,
type_field: String::from("u32"),
..Default::default()
},
),
]
.into_iter()
.collect::<HashMap<_, _>>();
let log_id = "42".to_string();
let actual = expand_custom_enum(
&FullTypeDeclaration::from_counterpart(&p, &types),
false,
Some(&log_id),
)?;
let expected = quote! {
#[allow(clippy::enum_variant_names)]
#[derive(
Clone,
Debug,
Eq,
PartialEq,
::fuels::macros::Parameterize,
::fuels::macros::Tokenizable,
::fuels::macros::TryFrom,
)]
pub enum EnumLevel3 {
El2(self::EnumLevel2),
}
impl ::fuels::core::codec::Log for EnumLevel3 {
const LOG_ID: &'static str = "42";
const LOG_ID_U64: u64 = 42u64;
}
};
assert_eq!(actual.code().to_string(), expected.to_string());
Ok(())
}
#[test]
fn test_expand_custom_struct() -> Result<()> {
let p = UnifiedTypeDeclaration {
type_field: String::from("struct Cocktail"),
components: Some(vec![
UnifiedTypeApplication {
name: String::from("long_island"),
type_id: 1,
..Default::default()
},
UnifiedTypeApplication {
name: String::from("cosmopolitan"),
type_id: 2,
..Default::default()
},
UnifiedTypeApplication {
name: String::from("mojito"),
type_id: 3,
..Default::default()
},
]),
..Default::default()
};
let types = [
(0, p.clone()),
(
1,
UnifiedTypeDeclaration {
type_id: 1,
type_field: String::from("bool"),
..Default::default()
},
),
(
2,
UnifiedTypeDeclaration {
type_id: 2,
type_field: String::from("u64"),
..Default::default()
},
),
(
3,
UnifiedTypeDeclaration {
type_id: 3,
type_field: String::from("u32"),
..Default::default()
},
),
]
.into_iter()
.collect::<HashMap<_, _>>();
let actual = expand_custom_struct(
&FullTypeDeclaration::from_counterpart(&p, &types),
false,
None,
)?;
let expected = quote! {
#[derive(
Clone,
Debug,
Eq,
PartialEq,
::fuels::macros::Parameterize,
::fuels::macros::Tokenizable,
::fuels::macros::TryFrom,
)]
pub struct Cocktail {
pub long_island: ::core::primitive::bool,
pub cosmopolitan: ::core::primitive::u64,
pub mojito: ::core::primitive::u32,
}
impl Cocktail {
pub fn new(
long_island: ::core::primitive::bool,
cosmopolitan: ::core::primitive::u64,
mojito: ::core::primitive::u32,
) -> Self {
Self {
long_island,
cosmopolitan,
mojito,
}
}
}
};
assert_eq!(actual.code().to_string(), expected.to_string());
Ok(())
}
#[test]
fn test_struct_with_no_fields_can_be_constructed() -> Result<()> {
let p = UnifiedTypeDeclaration {
type_id: 0,
type_field: "struct SomeEmptyStruct".to_string(),
components: Some(vec![]),
..Default::default()
};
let types = [(0, p.clone())].into_iter().collect::<HashMap<_, _>>();
let actual = expand_custom_struct(
&FullTypeDeclaration::from_counterpart(&p, &types),
false,
None,
)?;
let expected = quote! {
#[derive(
Clone,
Debug,
Eq,
PartialEq,
::core::default::Default,
::fuels::macros::Parameterize,
::fuels::macros::Tokenizable,
::fuels::macros::TryFrom,
)]
pub struct SomeEmptyStruct {}
impl SomeEmptyStruct {
pub fn new() -> Self {
Self {}
}
}
};
assert_eq!(actual.code().to_string(), expected.to_string());
Ok(())
}
#[test]
fn test_expand_custom_struct_with_struct() -> Result<()> {
let p = UnifiedTypeDeclaration {
type_id: 0,
type_field: String::from("struct Cocktail"),
components: Some(vec![
UnifiedTypeApplication {
name: String::from("long_island"),
type_id: 1,
..Default::default()
},
UnifiedTypeApplication {
name: String::from("mojito"),
type_id: 2,
..Default::default()
},
]),
..Default::default()
};
let types = [
(0, p.clone()),
(
1,
UnifiedTypeDeclaration {
type_id: 1,
type_field: String::from("struct Shaker"),
components: Some(vec![]),
..Default::default()
},
),
(
2,
UnifiedTypeDeclaration {
type_id: 2,
type_field: String::from("u32"),
..Default::default()
},
),
]
.into_iter()
.collect::<HashMap<_, _>>();
let log_id = "13".to_string();
let actual = expand_custom_struct(
&FullTypeDeclaration::from_counterpart(&p, &types),
false,
Some(&log_id),
)?;
let expected = quote! {
#[derive(
Clone,
Debug,
Eq,
PartialEq,
::fuels::macros::Parameterize,
::fuels::macros::Tokenizable,
::fuels::macros::TryFrom,
)]
pub struct Cocktail {
pub long_island: self::Shaker,
pub mojito: ::core::primitive::u32,
}
impl Cocktail {
pub fn new(long_island: self::Shaker, mojito: ::core::primitive::u32,) -> Self {
Self {
long_island,
mojito,
}
}
}
impl ::fuels::core::codec::Log for Cocktail {
const LOG_ID: &'static str = "13";
const LOG_ID_U64: u64 = 13u64;
}
};
assert_eq!(actual.code().to_string(), expected.to_string());
Ok(())
}
#[test]
fn shared_types_are_just_reexported() {
// given
let type_decl = FullTypeDeclaration {
type_field: "struct some_shared_lib::SharedStruct".to_string(),
components: vec![],
type_parameters: vec![],
alias_of: None,
};
let shared_types = HashSet::from([type_decl.clone()]);
// when
let generated_code = generate_types(&[type_decl], &shared_types, [], false).unwrap();
// then
let expected_code = quote! {
#[allow(clippy::too_many_arguments)]
#[allow(clippy::disallowed_names)]
#[no_implicit_prelude]
pub mod some_shared_lib {
use ::core::{
clone::Clone,
convert::{Into, TryFrom, From},
iter::IntoIterator,
iter::Iterator,
marker::Sized,
panic,
};
use ::std::{string::ToString, format, vec, default::Default};
pub use super::super::shared_types::some_shared_lib::SharedStruct;
}
};
assert_eq!(generated_code.code().to_string(), expected_code.to_string());
}
}
| rust | Apache-2.0 | 865e00c295de8b4a0a1ef7ac926c3c8266d5151b | 2026-01-04T15:31:59.450823Z | false |
FuelLabs/fuels-rs | https://github.com/FuelLabs/fuels-rs/blob/865e00c295de8b4a0a1ef7ac926c3c8266d5151b/packages/fuels-code-gen/src/program_bindings/abigen/abigen_target.rs | packages/fuels-code-gen/src/program_bindings/abigen/abigen_target.rs | use std::{
convert::TryFrom,
env, fs,
path::{Path, PathBuf},
str::FromStr,
};
use fuel_abi_types::abi::full_program::FullProgramABI;
use proc_macro2::Ident;
use crate::error::{Error, Result, error};
#[derive(Debug, Clone)]
pub struct AbigenTarget {
pub(crate) name: String,
pub(crate) source: Abi,
pub(crate) program_type: ProgramType,
}
impl AbigenTarget {
pub fn new(name: String, source: Abi, program_type: ProgramType) -> Self {
Self {
name,
source,
program_type,
}
}
pub fn name(&self) -> &str {
&self.name
}
pub fn source(&self) -> &Abi {
&self.source
}
pub fn program_type(&self) -> ProgramType {
self.program_type
}
}
#[derive(Debug, Clone)]
pub struct Abi {
pub(crate) path: Option<PathBuf>,
pub(crate) abi: FullProgramABI,
}
impl Abi {
pub fn load_from(path: impl AsRef<Path>) -> Result<Abi> {
let path = Self::canonicalize_path(path.as_ref())?;
let json_abi = fs::read_to_string(&path).map_err(|e| {
error!(
"failed to read `abi` file with path {}: {}",
path.display(),
e
)
})?;
let abi = Self::parse_from_json(&json_abi)?;
Ok(Abi {
path: Some(path),
abi,
})
}
fn canonicalize_path(path: &Path) -> Result<PathBuf> {
let current_dir = env::current_dir()
.map_err(|e| error!("unable to get current directory: ").combine(e))?;
let root = current_dir.canonicalize().map_err(|e| {
error!(
"unable to canonicalize current directory {}: ",
current_dir.display()
)
.combine(e)
})?;
let path = root.join(path);
if path.is_relative() {
path.canonicalize().map_err(|e| {
error!(
"unable to canonicalize file from working dir {} with path {}: {}",
env::current_dir()
.map(|cwd| cwd.display().to_string())
.unwrap_or_else(|err| format!("??? ({err})")),
path.display(),
e
)
})
} else {
Ok(path)
}
}
fn parse_from_json(json_abi: &str) -> Result<FullProgramABI> {
FullProgramABI::from_json_abi(json_abi)
.map_err(|e| error!("malformed `abi`. Did you use `forc` to create it?: ").combine(e))
}
pub fn path(&self) -> Option<&PathBuf> {
self.path.as_ref()
}
pub fn abi(&self) -> &FullProgramABI {
&self.abi
}
}
impl FromStr for Abi {
type Err = Error;
fn from_str(json_abi: &str) -> Result<Self> {
let abi = Abi::parse_from_json(json_abi)?;
Ok(Abi { path: None, abi })
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ProgramType {
Script,
Contract,
Predicate,
}
impl FromStr for ProgramType {
type Err = Error;
fn from_str(string: &str) -> std::result::Result<Self, Self::Err> {
let program_type = match string {
"Script" => ProgramType::Script,
"Contract" => ProgramType::Contract,
"Predicate" => ProgramType::Predicate,
_ => {
return Err(error!(
"`{string}` is not a valid program type. Expected one of: `Script`, `Contract`, `Predicate`"
));
}
};
Ok(program_type)
}
}
impl TryFrom<Ident> for ProgramType {
type Error = syn::Error;
fn try_from(ident: Ident) -> std::result::Result<Self, Self::Error> {
ident
.to_string()
.as_str()
.parse()
.map_err(|e| Self::Error::new(ident.span(), e))
}
}
| rust | Apache-2.0 | 865e00c295de8b4a0a1ef7ac926c3c8266d5151b | 2026-01-04T15:31:59.450823Z | false |
FuelLabs/fuels-rs | https://github.com/FuelLabs/fuels-rs/blob/865e00c295de8b4a0a1ef7ac926c3c8266d5151b/packages/fuels-code-gen/src/program_bindings/abigen/bindings.rs | packages/fuels-code-gen/src/program_bindings/abigen/bindings.rs | use crate::{
error::Result,
program_bindings::{
abigen::{
ProgramType,
abigen_target::AbigenTarget,
bindings::{
contract::contract_bindings, predicate::predicate_bindings, script::script_bindings,
},
},
generated_code::GeneratedCode,
},
utils::ident,
};
mod contract;
mod function_generator;
mod predicate;
mod script;
mod utils;
pub(crate) fn generate_bindings(target: AbigenTarget, no_std: bool) -> Result<GeneratedCode> {
let bindings_generator = match target.program_type {
ProgramType::Script => script_bindings,
ProgramType::Contract => contract_bindings,
ProgramType::Predicate => predicate_bindings,
};
let name = ident(&target.name);
let abi = target.source.abi;
bindings_generator(&name, abi, no_std)
}
| rust | Apache-2.0 | 865e00c295de8b4a0a1ef7ac926c3c8266d5151b | 2026-01-04T15:31:59.450823Z | false |
FuelLabs/fuels-rs | https://github.com/FuelLabs/fuels-rs/blob/865e00c295de8b4a0a1ef7ac926c3c8266d5151b/packages/fuels-code-gen/src/program_bindings/abigen/configurables.rs | packages/fuels-code-gen/src/program_bindings/abigen/configurables.rs | use fuel_abi_types::abi::full_program::FullConfigurable;
use proc_macro2::{Ident, TokenStream};
use quote::quote;
use crate::{
error::Result,
program_bindings::resolved_type::{ResolvedType, TypeResolver},
utils::safe_ident,
};
#[derive(Debug)]
pub(crate) struct ResolvedConfigurable {
pub name: Ident,
pub ttype: ResolvedType,
pub offset: u64,
}
impl ResolvedConfigurable {
pub fn new(configurable: &FullConfigurable) -> Result<ResolvedConfigurable> {
let type_application = &configurable.application;
Ok(ResolvedConfigurable {
name: safe_ident(&format!("with_{}", configurable.name)),
ttype: TypeResolver::default().resolve(type_application)?,
offset: configurable.offset,
})
}
}
pub(crate) fn generate_code_for_configurable_constants(
configurable_struct_name: &Ident,
configurables: &[FullConfigurable],
) -> Result<TokenStream> {
let resolved_configurables = configurables
.iter()
.map(ResolvedConfigurable::new)
.collect::<Result<Vec<_>>>()?;
let struct_decl = generate_struct_decl(configurable_struct_name);
let struct_impl = generate_struct_impl(configurable_struct_name, &resolved_configurables);
let from_impl = generate_from_impl(configurable_struct_name);
Ok(quote! {
#struct_decl
#struct_impl
#from_impl
})
}
fn generate_struct_decl(configurable_struct_name: &Ident) -> TokenStream {
quote! {
#[derive(Clone, Debug, Default)]
pub struct #configurable_struct_name {
offsets_with_data: ::std::vec::Vec<::fuels::core::Configurable>,
encoder: ::fuels::core::codec::ABIEncoder,
}
}
}
fn generate_struct_impl(
configurable_struct_name: &Ident,
resolved_configurables: &[ResolvedConfigurable],
) -> TokenStream {
let builder_methods = generate_builder_methods(resolved_configurables);
quote! {
impl #configurable_struct_name {
pub fn new(encoder_config: ::fuels::core::codec::EncoderConfig) -> Self {
Self {
encoder: ::fuels::core::codec::ABIEncoder::new(encoder_config),
..::std::default::Default::default()
}
}
#builder_methods
}
}
}
fn generate_builder_methods(resolved_configurables: &[ResolvedConfigurable]) -> TokenStream {
let methods = resolved_configurables.iter().map(
|ResolvedConfigurable {
name,
ttype,
offset,
}| {
let encoder_code = generate_encoder_code(ttype);
quote! {
#[allow(non_snake_case)]
// Generate the `with_XXX` methods for setting the configurables
pub fn #name(mut self, value: #ttype) -> ::fuels::prelude::Result<Self> {
let encoded = #encoder_code?;
self.offsets_with_data.push(::fuels::core::Configurable {
offset: #offset,
data: encoded,
});
::fuels::prelude::Result::Ok(self)
}
}
},
);
quote! {
#(#methods)*
}
}
fn generate_encoder_code(ttype: &ResolvedType) -> TokenStream {
quote! {
self.encoder.encode(&[
<#ttype as ::fuels::core::traits::Tokenizable>::into_token(value)
])
}
}
fn generate_from_impl(configurable_struct_name: &Ident) -> TokenStream {
quote! {
impl From<#configurable_struct_name> for ::fuels::core::Configurables {
fn from(config: #configurable_struct_name) -> Self {
::fuels::core::Configurables::new(config.offsets_with_data)
}
}
impl From<#configurable_struct_name> for ::std::vec::Vec<::fuels::core::Configurable> {
fn from(config: #configurable_struct_name) -> ::std::vec::Vec<::fuels::core::Configurable> {
config.offsets_with_data
}
}
}
}
| rust | Apache-2.0 | 865e00c295de8b4a0a1ef7ac926c3c8266d5151b | 2026-01-04T15:31:59.450823Z | false |
FuelLabs/fuels-rs | https://github.com/FuelLabs/fuels-rs/blob/865e00c295de8b4a0a1ef7ac926c3c8266d5151b/packages/fuels-code-gen/src/program_bindings/abigen/logs.rs | packages/fuels-code-gen/src/program_bindings/abigen/logs.rs | use fuel_abi_types::abi::full_program::FullLoggedType;
use proc_macro2::TokenStream;
use quote::quote;
use crate::program_bindings::resolved_type::TypeResolver;
pub(crate) fn log_formatters_instantiation_code(
contract_id: TokenStream,
logged_types: &[FullLoggedType],
) -> TokenStream {
let resolved_logs = resolve_logs(logged_types);
let log_id_log_formatter_pairs = generate_log_id_log_formatter_pairs(&resolved_logs);
quote! {::fuels::core::codec::log_formatters_lookup(vec![#(#log_id_log_formatter_pairs),*], #contract_id)}
}
#[derive(Debug)]
struct ResolvedLog {
log_id: String,
log_formatter: TokenStream,
}
/// Reads the parsed logged types from the ABI and creates ResolvedLogs
fn resolve_logs(logged_types: &[FullLoggedType]) -> Vec<ResolvedLog> {
logged_types
.iter()
.map(|l| {
let resolved_type = TypeResolver::default()
.resolve(&l.application)
.expect("Failed to resolve log type");
let is_error_type = l
.application
.type_decl
.components
.iter()
.any(|component| component.error_message.is_some());
let log_formatter = if is_error_type {
quote! {
::fuels::core::codec::LogFormatter::new_error::<#resolved_type>()
}
} else {
quote! {
::fuels::core::codec::LogFormatter::new_log::<#resolved_type>()
}
};
ResolvedLog {
log_id: l.log_id.clone(),
log_formatter,
}
})
.collect()
}
fn generate_log_id_log_formatter_pairs(
resolved_logs: &[ResolvedLog],
) -> impl Iterator<Item = TokenStream> {
resolved_logs.iter().map(|r| {
let id = &r.log_id;
let log_formatter = &r.log_formatter;
quote! {
(#id.to_string(), #log_formatter)
}
})
}
pub(crate) fn generate_id_error_codes_pairs(
error_codes: impl IntoIterator<Item = (u64, fuel_abi_types::abi::program::ErrorDetails)>,
) -> impl Iterator<Item = TokenStream> {
error_codes.into_iter().map(|(id, ed)| {
let pkg = ed.pos.pkg;
let file = ed.pos.file;
let line = ed.pos.line;
let column = ed.pos.column;
let log_id = ed.log_id.map_or(
quote! {::core::option::Option::None},
|l| quote! {::core::option::Option::Some(#l.to_string())},
);
let msg = ed.msg.map_or(
quote! {::core::option::Option::None},
|m| quote! {::core::option::Option::Some(#m.to_string())},
);
quote! {
(#id,
::fuels::core::codec::ErrorDetails::new(
#pkg.to_string(), #file.to_string(), #line, #column, #log_id, #msg
)
)
}
})
}
| rust | Apache-2.0 | 865e00c295de8b4a0a1ef7ac926c3c8266d5151b | 2026-01-04T15:31:59.450823Z | false |
FuelLabs/fuels-rs | https://github.com/FuelLabs/fuels-rs/blob/865e00c295de8b4a0a1ef7ac926c3c8266d5151b/packages/fuels-code-gen/src/program_bindings/abigen/bindings/contract.rs | packages/fuels-code-gen/src/program_bindings/abigen/bindings/contract.rs | use fuel_abi_types::abi::full_program::{FullABIFunction, FullProgramABI};
use itertools::Itertools;
use proc_macro2::{Ident, TokenStream};
use quote::{TokenStreamExt, quote};
use crate::{
error::Result,
program_bindings::{
abigen::{
bindings::function_generator::FunctionGenerator,
configurables::generate_code_for_configurable_constants,
logs::{generate_id_error_codes_pairs, log_formatters_instantiation_code},
},
generated_code::GeneratedCode,
},
utils::{TypePath, ident},
};
pub(crate) fn contract_bindings(
name: &Ident,
abi: FullProgramABI,
no_std: bool,
) -> Result<GeneratedCode> {
if no_std {
return Ok(GeneratedCode::default());
}
let log_formatters =
log_formatters_instantiation_code(quote! {contract_id.clone().into()}, &abi.logged_types);
let error_codes = generate_id_error_codes_pairs(abi.error_codes);
let error_codes = quote! {::std::collections::HashMap::from([#(#error_codes),*])};
let methods_name = ident(&format!("{name}Methods"));
let contract_methods_name = ident(&format!("{name}MethodVariants"));
let contract_functions = expand_functions(&abi.functions)?;
let constant_methods_code =
generate_constant_methods_pattern(&abi.functions, &contract_methods_name)?;
let configuration_struct_name = ident(&format!("{name}Configurables"));
let constant_configuration_code =
generate_code_for_configurable_constants(&configuration_struct_name, &abi.configurables)?;
let code = quote! {
#[derive(Debug, Clone)]
pub struct #name<A = ()> {
contract_id: ::fuels::types::ContractId,
account: A,
log_decoder: ::fuels::core::codec::LogDecoder,
encoder_config: ::fuels::core::codec::EncoderConfig,
}
impl #name {
pub const METHODS: #contract_methods_name = #contract_methods_name;
}
impl<A> #name<A>
{
pub fn new(
contract_id: ::fuels::types::ContractId,
account: A,
) -> Self {
let log_decoder = ::fuels::core::codec::LogDecoder::new(#log_formatters, #error_codes);
let encoder_config = ::fuels::core::codec::EncoderConfig::default();
Self { contract_id, account, log_decoder, encoder_config }
}
pub fn contract_id(&self) -> ::fuels::types::ContractId {
self.contract_id
}
pub fn account(&self) -> &A {
&self.account
}
pub fn with_account<U: ::fuels::accounts::Account>(self, account: U)
-> #name<U> {
#name {
contract_id: self.contract_id,
account,
log_decoder: self.log_decoder,
encoder_config: self.encoder_config
}
}
pub fn with_encoder_config(mut self, encoder_config: ::fuels::core::codec::EncoderConfig)
-> #name::<A> {
self.encoder_config = encoder_config;
self
}
pub async fn get_balances(&self) -> ::fuels::types::errors::Result<::std::collections::HashMap<::fuels::types::AssetId, u64>> where A: ::fuels::accounts::ViewOnlyAccount {
::fuels::accounts::ViewOnlyAccount::try_provider(&self.account)?
.get_contract_balances(&self.contract_id)
.await
.map_err(::std::convert::Into::into)
}
pub fn methods(&self) -> #methods_name<A> where A: Clone {
#methods_name {
contract_id: self.contract_id.clone(),
account: self.account.clone(),
log_decoder: self.log_decoder.clone(),
encoder_config: self.encoder_config.clone(),
}
}
}
// Implement struct that holds the contract methods
pub struct #methods_name<A> {
contract_id: ::fuels::types::ContractId,
account: A,
log_decoder: ::fuels::core::codec::LogDecoder,
encoder_config: ::fuels::core::codec::EncoderConfig,
}
impl<A: ::fuels::accounts::Account + Clone> #methods_name<A> {
#contract_functions
}
impl<A>
::fuels::programs::calls::ContractDependency for #name<A>
{
fn id(&self) -> ::fuels::types::ContractId {
self.contract_id
}
fn log_decoder(&self) -> ::fuels::core::codec::LogDecoder {
self.log_decoder.clone()
}
}
#constant_configuration_code
#constant_methods_code
};
// All publicly available types generated above should be listed here.
let type_paths = [
name,
&methods_name,
&configuration_struct_name,
&contract_methods_name,
]
.map(|type_name| TypePath::new(type_name).expect("We know the given types are not empty"))
.into_iter()
.collect();
Ok(GeneratedCode::new(code, type_paths, no_std))
}
fn expand_functions(functions: &[FullABIFunction]) -> Result<TokenStream> {
functions
.iter()
.map(expand_fn)
.fold_ok(TokenStream::default(), |mut all_code, code| {
all_code.append_all(code);
all_code
})
}
/// Transforms a function defined in [`FullABIFunction`] into a [`TokenStream`]
/// that represents that same function signature as a Rust-native function
/// declaration.
pub(crate) fn expand_fn(abi_fun: &FullABIFunction) -> Result<TokenStream> {
let mut generator = FunctionGenerator::new(abi_fun)?;
generator.set_docs(abi_fun.doc_strings()?);
let original_output = generator.output_type();
generator.set_output_type(
quote! {::fuels::programs::calls::CallHandler<A, ::fuels::programs::calls::ContractCall, #original_output> },
);
let fn_selector = generator.fn_selector();
let arg_tokens = generator.tokenized_args();
let is_payable = abi_fun.is_payable();
let body = quote! {
::fuels::programs::calls::CallHandler::new_contract_call(
self.contract_id.clone(),
self.account.clone(),
#fn_selector,
&#arg_tokens,
self.log_decoder.clone(),
#is_payable,
self.encoder_config.clone(),
)
};
generator.set_body(body);
Ok(generator.generate())
}
fn generate_constant_methods_pattern(
functions: &[FullABIFunction],
contract_methods_name: &Ident,
) -> Result<TokenStream> {
let method_descriptors = functions.iter().map(|func| {
let method_name = ident(func.name());
let fn_name = func.name();
let fn_selector =
proc_macro2::Literal::byte_string(&crate::utils::encode_fn_selector(fn_name));
quote! {
pub const fn #method_name(&self) -> ::fuels::types::MethodDescriptor {
::fuels::types::MethodDescriptor {
name: #fn_name,
fn_selector: #fn_selector,
}
}
}
});
let all_methods = functions.iter().map(|func| {
let method_name = ident(func.name());
quote! { Self.#method_name() }
});
let method_count = functions.len();
let code = quote! {
#[derive(Debug, Clone, Copy)]
pub struct #contract_methods_name;
impl #contract_methods_name {
#(#method_descriptors)*
pub const fn iter(&self) -> [::fuels::types::MethodDescriptor; #method_count] {
[#(#all_methods),*]
}
}
};
Ok(code)
}
#[cfg(test)]
mod tests {
use std::collections::HashMap;
use fuel_abi_types::abi::{
full_program::FullABIFunction,
program::Attribute,
unified_program::{UnifiedABIFunction, UnifiedTypeApplication, UnifiedTypeDeclaration},
};
use pretty_assertions::assert_eq;
use quote::quote;
use crate::{error::Result, program_bindings::abigen::bindings::contract::expand_fn};
#[test]
fn expand_contract_method_simple() -> Result<()> {
let the_function = UnifiedABIFunction {
inputs: vec![UnifiedTypeApplication {
name: String::from("bimbam"),
type_id: 1,
..Default::default()
}],
name: "hello_world".to_string(),
attributes: Some(vec![Attribute {
name: "doc-comment".to_string(),
arguments: vec!["This is a doc string".to_string()],
}]),
..Default::default()
};
let types = [
(
0,
UnifiedTypeDeclaration {
type_id: 0,
type_field: String::from("()"),
..Default::default()
},
),
(
1,
UnifiedTypeDeclaration {
type_id: 1,
type_field: String::from("bool"),
..Default::default()
},
),
]
.into_iter()
.collect::<HashMap<_, _>>();
let result = expand_fn(&FullABIFunction::from_counterpart(&the_function, &types)?);
let expected = quote! {
#[doc = "This is a doc string"]
pub fn hello_world(&self, bimbam: ::core::primitive::bool) -> ::fuels::programs::calls::CallHandler<A, ::fuels::programs::calls::ContractCall, ()> {
::fuels::programs::calls::CallHandler::new_contract_call(
self.contract_id.clone(),
self.account.clone(),
::fuels::core::codec::encode_fn_selector("hello_world"),
&[::fuels::core::traits::Tokenizable::into_token(bimbam)],
self.log_decoder.clone(),
false,
self.encoder_config.clone(),
)
}
};
assert_eq!(result?.to_string(), expected.to_string());
Ok(())
}
#[test]
fn expand_contract_method_complex() -> Result<()> {
// given
let the_function = UnifiedABIFunction {
inputs: vec![UnifiedTypeApplication {
name: String::from("the_only_allowed_input"),
type_id: 4,
..Default::default()
}],
name: "hello_world".to_string(),
output: UnifiedTypeApplication {
name: String::from("stillnotused"),
type_id: 1,
..Default::default()
},
attributes: Some(vec![
Attribute {
name: "doc-comment".to_string(),
arguments: vec!["This is a doc string".to_string()],
},
Attribute {
name: "doc-comment".to_string(),
arguments: vec!["This is another doc string".to_string()],
},
]),
};
let types = [
(
1,
UnifiedTypeDeclaration {
type_id: 1,
type_field: String::from("enum EntropyCirclesEnum"),
components: Some(vec![
UnifiedTypeApplication {
name: String::from("Postcard"),
type_id: 2,
..Default::default()
},
UnifiedTypeApplication {
name: String::from("Teacup"),
type_id: 3,
..Default::default()
},
]),
..Default::default()
},
),
(
2,
UnifiedTypeDeclaration {
type_id: 2,
type_field: String::from("bool"),
..Default::default()
},
),
(
3,
UnifiedTypeDeclaration {
type_id: 3,
type_field: String::from("u64"),
..Default::default()
},
),
(
4,
UnifiedTypeDeclaration {
type_id: 4,
type_field: String::from("struct SomeWeirdFrenchCuisine"),
components: Some(vec![
UnifiedTypeApplication {
name: String::from("Beef"),
type_id: 2,
..Default::default()
},
UnifiedTypeApplication {
name: String::from("BurgundyWine"),
type_id: 3,
..Default::default()
},
]),
..Default::default()
},
),
]
.into_iter()
.collect::<HashMap<_, _>>();
// when
let result = expand_fn(&FullABIFunction::from_counterpart(&the_function, &types)?);
// then
// Some more editing was required because it is not rustfmt-compatible (adding/removing parentheses or commas)
let expected = quote! {
#[doc = "This is a doc string"]
#[doc = "This is another doc string"]
pub fn hello_world(
&self,
the_only_allowed_input: self::SomeWeirdFrenchCuisine
) -> ::fuels::programs::calls::CallHandler<A, ::fuels::programs::calls::ContractCall, self::EntropyCirclesEnum> {
::fuels::programs::calls::CallHandler::new_contract_call(
self.contract_id.clone(),
self.account.clone(),
::fuels::core::codec::encode_fn_selector( "hello_world"),
&[::fuels::core::traits::Tokenizable::into_token(
the_only_allowed_input
)],
self.log_decoder.clone(),
false,
self.encoder_config.clone(),
)
}
};
assert_eq!(result?.to_string(), expected.to_string());
Ok(())
}
}
| rust | Apache-2.0 | 865e00c295de8b4a0a1ef7ac926c3c8266d5151b | 2026-01-04T15:31:59.450823Z | false |
FuelLabs/fuels-rs | https://github.com/FuelLabs/fuels-rs/blob/865e00c295de8b4a0a1ef7ac926c3c8266d5151b/packages/fuels-code-gen/src/program_bindings/abigen/bindings/predicate.rs | packages/fuels-code-gen/src/program_bindings/abigen/bindings/predicate.rs | use fuel_abi_types::abi::full_program::{FullABIFunction, FullProgramABI};
use proc_macro2::{Ident, TokenStream};
use quote::quote;
use crate::{
error::Result,
program_bindings::{
abigen::{
bindings::{function_generator::FunctionGenerator, utils::extract_main_fn},
configurables::generate_code_for_configurable_constants,
},
generated_code::GeneratedCode,
},
utils::{TypePath, ident},
};
pub(crate) fn predicate_bindings(
name: &Ident,
abi: FullProgramABI,
no_std: bool,
) -> Result<GeneratedCode> {
let main_function_abi = extract_main_fn(&abi.functions)?;
let encode_function = expand_fn(main_function_abi)?;
let encoder_struct_name = ident(&format!("{name}Encoder"));
let configuration_struct_name = ident(&format!("{name}Configurables"));
let constant_configuration_code =
generate_code_for_configurable_constants(&configuration_struct_name, &abi.configurables)?;
let code = quote! {
#[derive(Default)]
pub struct #encoder_struct_name{
encoder: ::fuels::core::codec::ABIEncoder,
}
impl #encoder_struct_name {
#encode_function
pub fn new(encoder_config: ::fuels::core::codec::EncoderConfig) -> Self {
Self {
encoder: ::fuels::core::codec::ABIEncoder::new(encoder_config)
}
}
}
#constant_configuration_code
};
// All publicly available types generated above should be listed here.
let type_paths = [&encoder_struct_name, &configuration_struct_name]
.map(|type_name| TypePath::new(type_name).expect("We know the given types are not empty"))
.into_iter()
.collect();
Ok(GeneratedCode::new(code, type_paths, no_std))
}
fn expand_fn(fn_abi: &FullABIFunction) -> Result<TokenStream> {
let mut generator = FunctionGenerator::new(fn_abi)?;
let arg_tokens = generator.tokenized_args();
let body = quote! {
self.encoder.encode(&#arg_tokens)
};
let output_type = quote! {
::fuels::types::errors::Result<::std::vec::Vec<u8>>
};
generator
.set_docs(vec!["Encode the predicate arguments".to_string()])
.set_name("encode_data".to_string())
.set_output_type(output_type)
.set_body(body);
Ok(generator.generate())
}
| rust | Apache-2.0 | 865e00c295de8b4a0a1ef7ac926c3c8266d5151b | 2026-01-04T15:31:59.450823Z | false |
FuelLabs/fuels-rs | https://github.com/FuelLabs/fuels-rs/blob/865e00c295de8b4a0a1ef7ac926c3c8266d5151b/packages/fuels-code-gen/src/program_bindings/abigen/bindings/utils.rs | packages/fuels-code-gen/src/program_bindings/abigen/bindings/utils.rs | use fuel_abi_types::abi::full_program::FullABIFunction;
use crate::error::{Result, error};
pub(crate) fn extract_main_fn(abi: &[FullABIFunction]) -> Result<&FullABIFunction> {
let candidates = abi
.iter()
.filter(|function| function.name() == "main")
.collect::<Vec<_>>();
match candidates.as_slice() {
[single_main_fn] => Ok(single_main_fn),
_ => {
let fn_names = abi
.iter()
.map(|candidate| candidate.name())
.collect::<Vec<_>>();
Err(error!(
"`abi` must have only one function with the name 'main'. Got: {fn_names:?}"
))
}
}
}
#[cfg(test)]
mod tests {
use fuel_abi_types::abi::full_program::{FullTypeApplication, FullTypeDeclaration};
use super::*;
#[test]
fn correctly_extracts_the_main_fn() {
let functions = ["fn_1", "main", "fn_2"].map(given_a_fun_named);
let fun = extract_main_fn(&functions).expect("should have succeeded");
assert_eq!(*fun, functions[1]);
}
#[test]
fn fails_if_there_is_more_than_one_main_fn() {
let functions = ["main", "another", "main"].map(given_a_fun_named);
let err = extract_main_fn(&functions).expect_err("should have failed");
assert_eq!(
err.to_string(),
r#"`abi` must have only one function with the name 'main'. Got: ["main", "another", "main"]"#
);
}
fn given_a_fun_named(fn_name: &str) -> FullABIFunction {
FullABIFunction::new(
fn_name.to_string(),
vec![],
FullTypeApplication {
name: "".to_string(),
type_decl: FullTypeDeclaration {
type_field: "".to_string(),
components: vec![],
type_parameters: vec![],
alias_of: None,
},
type_arguments: vec![],
error_message: None,
},
vec![],
)
.expect("hand-crafted, should not fail!")
}
}
| rust | Apache-2.0 | 865e00c295de8b4a0a1ef7ac926c3c8266d5151b | 2026-01-04T15:31:59.450823Z | false |
FuelLabs/fuels-rs | https://github.com/FuelLabs/fuels-rs/blob/865e00c295de8b4a0a1ef7ac926c3c8266d5151b/packages/fuels-code-gen/src/program_bindings/abigen/bindings/function_generator.rs | packages/fuels-code-gen/src/program_bindings/abigen/bindings/function_generator.rs | use fuel_abi_types::abi::full_program::FullABIFunction;
use proc_macro2::TokenStream;
use quote::{ToTokens, quote};
use crate::{
error::Result,
program_bindings::{
resolved_type::TypeResolver,
utils::{Component, Components},
},
utils::{TypePath, safe_ident},
};
#[derive(Debug)]
pub(crate) struct FunctionGenerator {
name: String,
args: Components,
output_type: TokenStream,
body: TokenStream,
docs: Vec<String>,
}
impl FunctionGenerator {
pub fn new(fun: &FullABIFunction) -> Result<Self> {
// All abi-method-calling Rust functions are currently generated at the top-level-mod of
// the Program in question (e.g. abigen_bindings::my_contract_mod`). If we ever nest
// these functions in a deeper mod we would need to propagate the mod to here instead of
// just hard-coding the default path.
let args = Components::new(fun.inputs(), true, TypePath::default())?;
// We are not checking that the ABI contains non-SDK supported types so that the user can
// still interact with an ABI even if some methods will fail at runtime.
let output_type = TypeResolver::default().resolve(fun.output())?;
Ok(Self {
name: fun.name().to_string(),
args,
output_type: output_type.to_token_stream(),
body: Default::default(),
docs: vec![],
})
}
pub fn set_name(&mut self, name: String) -> &mut Self {
self.name = name;
self
}
pub fn set_body(&mut self, body: TokenStream) -> &mut Self {
self.body = body;
self
}
pub fn set_docs(&mut self, docs: Vec<String>) -> &mut Self {
self.docs = docs;
self
}
pub fn fn_selector(&self) -> TokenStream {
let name = &self.name;
quote! {::fuels::core::codec::encode_fn_selector(#name)}
}
pub fn tokenized_args(&self) -> TokenStream {
let arg_names = self.args.iter().map(|Component { ident, .. }| {
quote! {#ident}
});
quote! {[#(::fuels::core::traits::Tokenizable::into_token(#arg_names)),*]}
}
pub fn set_output_type(&mut self, output_type: TokenStream) -> &mut Self {
self.output_type = output_type;
self
}
pub fn output_type(&self) -> &TokenStream {
&self.output_type
}
pub fn generate(&self) -> TokenStream {
let name = safe_ident(&self.name);
let docs: Vec<TokenStream> = self
.docs
.iter()
.map(|doc| {
quote! { #[doc = #doc] }
})
.collect();
let arg_declarations = self.args.iter().map(
|Component {
ident,
resolved_type,
..
}| {
quote! { #ident: #resolved_type }
},
);
let output_type = self.output_type();
let body = &self.body;
let params = quote! { &self, #(#arg_declarations),* };
quote! {
#(#docs)*
pub fn #name(#params) -> #output_type {
#body
}
}
}
}
#[cfg(test)]
mod tests {
use fuel_abi_types::abi::full_program::{FullTypeApplication, FullTypeDeclaration};
use pretty_assertions::assert_eq;
use super::*;
#[test]
fn correct_fn_selector_resolving_code() -> Result<()> {
let function = given_a_fun();
let sut = FunctionGenerator::new(&function)?;
let fn_selector_code = sut.fn_selector();
let expected = quote! {
::fuels::core::codec::encode_fn_selector("test_function")
};
assert_eq!(fn_selector_code.to_string(), expected.to_string());
Ok(())
}
#[test]
fn correct_tokenized_args() -> Result<()> {
let function = given_a_fun();
let sut = FunctionGenerator::new(&function)?;
let tokenized_args = sut.tokenized_args();
assert_eq!(
tokenized_args.to_string(),
"[:: fuels :: core :: traits :: Tokenizable :: into_token (arg_0)]"
);
Ok(())
}
#[test]
fn tokenizes_correctly() -> Result<()> {
// given
let function = given_a_fun();
let mut sut = FunctionGenerator::new(&function)?;
sut.set_docs(vec![
" This is a doc".to_string(),
" This is another doc".to_string(),
])
.set_body(quote! {this is ze body});
// when
let tokenized: TokenStream = sut.generate();
// then
let expected = quote! {
#[doc = " This is a doc"]
#[doc = " This is another doc"]
pub fn test_function(&self, arg_0: self::CustomStruct<::core::primitive::u8>) -> self::CustomStruct<::core::primitive::u64> {
this is ze body
}
};
// then
assert_eq!(tokenized.to_string(), expected.to_string());
Ok(())
}
fn given_a_fun() -> FullABIFunction {
let generic_type_t = FullTypeDeclaration {
type_field: "generic T".to_string(),
components: vec![],
type_parameters: vec![],
alias_of: None,
};
let custom_struct_type = FullTypeDeclaration {
type_field: "struct CustomStruct".to_string(),
components: vec![FullTypeApplication {
name: "field_a".to_string(),
type_decl: generic_type_t.clone(),
type_arguments: vec![],
error_message: None,
}],
type_parameters: vec![generic_type_t],
alias_of: None,
};
let fn_output = FullTypeApplication {
name: "".to_string(),
type_decl: custom_struct_type.clone(),
type_arguments: vec![FullTypeApplication {
name: "".to_string(),
type_decl: FullTypeDeclaration {
type_field: "u64".to_string(),
components: vec![],
type_parameters: vec![],
alias_of: None,
},
type_arguments: vec![],
error_message: None,
}],
error_message: None,
};
let fn_inputs = vec![FullTypeApplication {
name: "arg_0".to_string(),
type_decl: custom_struct_type,
type_arguments: vec![FullTypeApplication {
name: "".to_string(),
type_decl: FullTypeDeclaration {
type_field: "u8".to_string(),
components: vec![],
type_parameters: vec![],
alias_of: None,
},
type_arguments: vec![],
error_message: None,
}],
error_message: None,
}];
FullABIFunction::new("test_function".to_string(), fn_inputs, fn_output, vec![])
.expect("Hand crafted function known to be correct")
}
}
| rust | Apache-2.0 | 865e00c295de8b4a0a1ef7ac926c3c8266d5151b | 2026-01-04T15:31:59.450823Z | false |
FuelLabs/fuels-rs | https://github.com/FuelLabs/fuels-rs/blob/865e00c295de8b4a0a1ef7ac926c3c8266d5151b/packages/fuels-code-gen/src/program_bindings/abigen/bindings/script.rs | packages/fuels-code-gen/src/program_bindings/abigen/bindings/script.rs | use std::default::Default;
use fuel_abi_types::abi::full_program::{FullABIFunction, FullProgramABI};
use proc_macro2::{Ident, TokenStream};
use quote::quote;
use crate::{
error::Result,
program_bindings::{
abigen::{
bindings::{function_generator::FunctionGenerator, utils::extract_main_fn},
configurables::generate_code_for_configurable_constants,
logs::{generate_id_error_codes_pairs, log_formatters_instantiation_code},
},
generated_code::GeneratedCode,
},
utils::{TypePath, ident},
};
pub(crate) fn script_bindings(
name: &Ident,
abi: FullProgramABI,
no_std: bool,
) -> Result<GeneratedCode> {
if no_std {
return Ok(GeneratedCode::default());
}
let main_function_abi = extract_main_fn(&abi.functions)?;
let main_function = expand_fn(main_function_abi)?;
let log_formatters = log_formatters_instantiation_code(
quote! {::fuels::types::ContractId::zeroed()},
&abi.logged_types,
);
let error_codes = generate_id_error_codes_pairs(abi.error_codes);
let error_codes = quote! {vec![#(#error_codes),*].into_iter().collect()};
let configuration_struct_name = ident(&format!("{name}Configurables"));
let constant_configuration_code =
generate_code_for_configurable_constants(&configuration_struct_name, &abi.configurables)?;
let code = quote! {
#[derive(Debug,Clone)]
pub struct #name<A>{
account: A,
unconfigured_binary: ::std::vec::Vec<u8>,
configurables: ::fuels::core::Configurables,
converted_into_loader: bool,
log_decoder: ::fuels::core::codec::LogDecoder,
encoder_config: ::fuels::core::codec::EncoderConfig,
}
impl<A> #name<A>
{
pub fn new(account: A, binary_filepath: &str) -> Self {
let binary = ::std::fs::read(binary_filepath)
.expect(&format!("could not read script binary {binary_filepath:?}"));
Self {
account,
unconfigured_binary: binary,
configurables: ::core::default::Default::default(),
converted_into_loader: false,
log_decoder: ::fuels::core::codec::LogDecoder::new(#log_formatters, #error_codes),
encoder_config: ::fuels::core::codec::EncoderConfig::default(),
}
}
pub fn with_account<U>(self, account: U) -> #name<U> {
#name {
account,
unconfigured_binary: self.unconfigured_binary,
log_decoder: self.log_decoder,
encoder_config: self.encoder_config,
configurables: self.configurables,
converted_into_loader: self.converted_into_loader,
}
}
pub fn with_configurables(mut self, configurables: impl Into<::fuels::core::Configurables>)
-> Self
{
self.configurables = configurables.into();
self
}
pub fn code(&self) -> ::std::vec::Vec<u8> {
let regular = ::fuels::programs::executable::Executable::from_bytes(self.unconfigured_binary.clone()).with_configurables(self.configurables.clone());
if self.converted_into_loader {
let loader = regular.convert_to_loader().expect("cannot fail since we already converted to the loader successfully");
loader.code()
} else {
regular.code()
}
}
pub fn account(&self) -> &A {
&self.account
}
pub fn with_encoder_config(mut self, encoder_config: ::fuels::core::codec::EncoderConfig)
-> Self
{
self.encoder_config = encoder_config;
self
}
pub fn log_decoder(&self) -> ::fuels::core::codec::LogDecoder {
self.log_decoder.clone()
}
/// Will upload the script code as a blob to the network and change the script code
/// into a loader that will fetch the blob and load it into memory before executing the
/// code inside. Allows you to optimize fees by paying for most of the code once and
/// then just running a small loader.
pub async fn convert_into_loader(&mut self) -> ::fuels::types::errors::Result<&mut Self> where A: ::fuels::accounts::Account + Clone {
if !self.converted_into_loader {
let regular = ::fuels::programs::executable::Executable::from_bytes(self.unconfigured_binary.clone()).with_configurables(self.configurables.clone());
let loader = regular.convert_to_loader()?;
loader.upload_blob(self.account.clone()).await?;
self.converted_into_loader = true;
}
::fuels::types::errors::Result::Ok(self)
}
}
impl<A: ::fuels::accounts::Account + Clone> #name<A> {
#main_function
}
#constant_configuration_code
};
// All publicly available types generated above should be listed here.
let type_paths = [name, &configuration_struct_name]
.map(|type_name| TypePath::new(type_name).expect("We know the given types are not empty"))
.into_iter()
.collect();
Ok(GeneratedCode::new(code, type_paths, no_std))
}
fn expand_fn(fn_abi: &FullABIFunction) -> Result<TokenStream> {
let mut generator = FunctionGenerator::new(fn_abi)?;
let arg_tokens = generator.tokenized_args();
let original_output_type = generator.output_type();
let body = quote! {
let encoded_args = ::fuels::core::codec::ABIEncoder::new(self.encoder_config).encode(&#arg_tokens);
::fuels::programs::calls::CallHandler::new_script_call(
self.code(),
encoded_args,
self.account.clone(),
self.log_decoder.clone()
)
};
generator
.set_output_type(quote! {::fuels::programs::calls::CallHandler<A, ::fuels::programs::calls::ScriptCall, #original_output_type> })
.set_docs(fn_abi.doc_strings()?)
.set_body(body);
Ok(generator.generate())
}
#[cfg(test)]
mod tests {
use std::collections::HashMap;
use fuel_abi_types::abi::{
full_program::FullABIFunction,
program::Attribute,
unified_program::{UnifiedABIFunction, UnifiedTypeApplication, UnifiedTypeDeclaration},
};
use pretty_assertions::assert_eq;
use quote::quote;
use crate::{error::Result, program_bindings::abigen::bindings::script::expand_fn};
#[test]
fn expand_script_main_function() -> Result<()> {
let the_function = UnifiedABIFunction {
inputs: vec![UnifiedTypeApplication {
name: String::from("bimbam"),
type_id: 1,
..Default::default()
}],
name: "main".to_string(),
attributes: Some(vec![
Attribute {
name: "doc-comment".to_string(),
arguments: vec!["This is a doc string".to_string()],
},
Attribute {
name: "doc-comment".to_string(),
arguments: vec!["This is another doc string".to_string()],
},
]),
..Default::default()
};
let types = [
(
0,
UnifiedTypeDeclaration {
type_id: 0,
type_field: String::from("()"),
..Default::default()
},
),
(
1,
UnifiedTypeDeclaration {
type_id: 1,
type_field: String::from("bool"),
..Default::default()
},
),
]
.into_iter()
.collect::<HashMap<_, _>>();
let result = expand_fn(&FullABIFunction::from_counterpart(&the_function, &types)?);
let expected = quote! {
#[doc = "This is a doc string"]
#[doc = "This is another doc string"]
pub fn main(&self, bimbam: ::core::primitive::bool) -> ::fuels::programs::calls::CallHandler<A, ::fuels::programs::calls::ScriptCall, ()> {
let encoded_args=::fuels::core::codec::ABIEncoder::new(self.encoder_config)
.encode(&[::fuels::core::traits::Tokenizable::into_token(bimbam)]);
::fuels::programs::calls::CallHandler::new_script_call(
self.code(),
encoded_args,
self.account.clone(),
self.log_decoder.clone()
)
}
};
assert_eq!(result?.to_string(), expected.to_string());
Ok(())
}
}
| rust | Apache-2.0 | 865e00c295de8b4a0a1ef7ac926c3c8266d5151b | 2026-01-04T15:31:59.450823Z | false |
FuelLabs/fuels-rs | https://github.com/FuelLabs/fuels-rs/blob/865e00c295de8b4a0a1ef7ac926c3c8266d5151b/packages/fuels-code-gen/src/program_bindings/custom_types/structs.rs | packages/fuels-code-gen/src/program_bindings/custom_types/structs.rs | use std::collections::HashSet;
use fuel_abi_types::abi::full_program::FullTypeDeclaration;
use proc_macro2::{Ident, TokenStream};
use quote::quote;
use crate::{
error::Result,
program_bindings::{
custom_types::utils::extract_generic_parameters,
generated_code::GeneratedCode,
resolved_type::ResolvedType,
utils::{Component, Components, tokenize_generics},
},
};
/// Returns a TokenStream containing the declaration, `Parameterize`,
/// `Tokenizable` and `TryFrom` implementations for the struct described by the
/// given TypeDeclaration.
pub(crate) fn expand_custom_struct(
type_decl: &FullTypeDeclaration,
no_std: bool,
log_id: Option<&String>,
) -> Result<GeneratedCode> {
let struct_type_path = type_decl.custom_type_path()?;
let struct_ident = struct_type_path.ident().unwrap();
let components = Components::new(&type_decl.components, true, struct_type_path.parent())?;
let generic_parameters = extract_generic_parameters(type_decl);
let code = struct_decl(
struct_ident,
&components,
&generic_parameters,
no_std,
log_id,
);
let struct_code = GeneratedCode::new(code, HashSet::from([struct_ident.into()]), no_std);
Ok(struct_code.wrap_in_mod(struct_type_path.parent()))
}
fn unzip_field_names_and_types(components: &Components) -> (Vec<&Ident>, Vec<&ResolvedType>) {
components
.iter()
.map(
|Component {
ident,
resolved_type,
..
}| (ident, resolved_type),
)
.unzip()
}
fn struct_decl(
struct_ident: &Ident,
components: &Components,
generics: &[Ident],
no_std: bool,
log_id: Option<&String>,
) -> TokenStream {
let derive_default = components
.is_empty()
.then(|| quote!(::core::default::Default,));
let maybe_disable_std = no_std.then(|| quote! {#[NoStd]});
let (generics_wo_bounds, generics_w_bounds) = tokenize_generics(generics);
let (field_names, field_types): (Vec<_>, Vec<_>) = unzip_field_names_and_types(components);
let (phantom_fields, phantom_types) =
components.generate_parameters_for_unused_generics(generics);
let log_impl = log_id.map(|log_id| {
let log_id_u64: u64 = log_id.parse::<u64>().expect("log id should be a valid u64 string");
quote! {
impl #generics_w_bounds ::fuels::core::codec::Log for #struct_ident #generics_wo_bounds {
const LOG_ID: &'static str = #log_id;
const LOG_ID_U64: u64 = #log_id_u64;
}
}
});
quote! {
#[derive(
Clone,
Debug,
Eq,
PartialEq,
#derive_default
::fuels::macros::Parameterize,
::fuels::macros::Tokenizable,
::fuels::macros::TryFrom,
)]
#maybe_disable_std
pub struct #struct_ident #generics_w_bounds {
#( pub #field_names: #field_types, )*
#(#[Ignore] pub #phantom_fields: #phantom_types, )*
}
impl #generics_w_bounds #struct_ident #generics_wo_bounds {
pub fn new(#(#field_names: #field_types,)*) -> Self {
Self {
#(#field_names,)*
#(#phantom_fields: ::core::default::Default::default(),)*
}
}
}
#log_impl
}
}
| rust | Apache-2.0 | 865e00c295de8b4a0a1ef7ac926c3c8266d5151b | 2026-01-04T15:31:59.450823Z | false |
FuelLabs/fuels-rs | https://github.com/FuelLabs/fuels-rs/blob/865e00c295de8b4a0a1ef7ac926c3c8266d5151b/packages/fuels-code-gen/src/program_bindings/custom_types/enums.rs | packages/fuels-code-gen/src/program_bindings/custom_types/enums.rs | use std::collections::HashSet;
use fuel_abi_types::abi::full_program::FullTypeDeclaration;
use proc_macro2::{Ident, TokenStream};
use quote::quote;
use crate::{
error::{Result, error},
program_bindings::{
custom_types::utils::extract_generic_parameters,
generated_code::GeneratedCode,
resolved_type::ResolvedType,
utils::{Component, Components, tokenize_generics},
},
};
/// Returns a TokenStream containing the declaration, `Parameterize`,
/// `Tokenizable` and `TryFrom` implementations for the enum described by the
/// given TypeDeclaration.
pub(crate) fn expand_custom_enum(
type_decl: &FullTypeDeclaration,
no_std: bool,
log_id: Option<&String>,
) -> Result<GeneratedCode> {
let enum_type_path = type_decl.custom_type_path()?;
let enum_ident = enum_type_path.ident().unwrap();
let components = Components::new(&type_decl.components, false, enum_type_path.parent())?;
if components.is_empty() {
return Err(error!("enum must have at least one component"));
}
let generics = extract_generic_parameters(type_decl);
let code = enum_decl(enum_ident, &components, &generics, no_std, log_id);
let enum_code = GeneratedCode::new(code, HashSet::from([enum_ident.into()]), no_std);
Ok(enum_code.wrap_in_mod(enum_type_path.parent()))
}
fn maybe_impl_error(enum_ident: &Ident, components: &Components) -> Option<TokenStream> {
components.has_error_messages().then(|| {
let display_match_branches = components.iter().map(|Component{ident, resolved_type, error_message}| {
let error_msg = error_message.as_deref().expect("error message is there - checked above");
if let ResolvedType::Unit = resolved_type {
quote! {#enum_ident::#ident => ::std::write!(f, "{}", #error_msg)}
} else {
quote! {#enum_ident::#ident(val) => ::std::write!(f, "{}: {:?}", #error_msg, val)}
}
});
let custom_display_impl = quote! {
impl ::std::fmt::Display for #enum_ident {
fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {
match &self {
#(#display_match_branches,)*
}
}
}
};
quote! {
#custom_display_impl
impl ::std::error::Error for #enum_ident{}
}
})
}
fn enum_decl(
enum_ident: &Ident,
components: &Components,
generics: &[Ident],
no_std: bool,
log_id: Option<&String>,
) -> TokenStream {
let maybe_disable_std = no_std.then(|| quote! {#[NoStd]});
let enum_variants = components.as_enum_variants();
let unused_generics_variant = components.generate_variant_for_unused_generics(generics);
let (generics_wo_bounds, generics_w_bounds) = tokenize_generics(generics);
let maybe_impl_error = maybe_impl_error(enum_ident, components);
let log_impl = log_id.map(|log_id| {
let log_id_u64: u64 = log_id
.parse::<u64>()
.expect("log id should be a valid u64 string");
quote! {
impl #generics_w_bounds ::fuels::core::codec::Log for #enum_ident #generics_wo_bounds {
const LOG_ID: &'static str = #log_id;
const LOG_ID_U64: u64 = #log_id_u64;
}
}
});
quote! {
#[allow(clippy::enum_variant_names)]
#[derive(
Clone,
Debug,
Eq,
PartialEq,
::fuels::macros::Parameterize,
::fuels::macros::Tokenizable,
::fuels::macros::TryFrom,
)]
#maybe_disable_std
pub enum #enum_ident #generics_w_bounds {
#(#enum_variants,)*
#unused_generics_variant
}
#maybe_impl_error
#log_impl
}
}
| rust | Apache-2.0 | 865e00c295de8b4a0a1ef7ac926c3c8266d5151b | 2026-01-04T15:31:59.450823Z | false |
FuelLabs/fuels-rs | https://github.com/FuelLabs/fuels-rs/blob/865e00c295de8b4a0a1ef7ac926c3c8266d5151b/packages/fuels-code-gen/src/program_bindings/custom_types/utils.rs | packages/fuels-code-gen/src/program_bindings/custom_types/utils.rs | use fuel_abi_types::{
abi::full_program::FullTypeDeclaration,
utils::{self, extract_generic_name},
};
use proc_macro2::Ident;
/// Returns a vector of TokenStreams, one for each of the generic parameters
/// used by the given type.
pub(crate) fn extract_generic_parameters(type_decl: &FullTypeDeclaration) -> Vec<Ident> {
type_decl
.type_parameters
.iter()
.map(|decl| {
let name = extract_generic_name(&decl.type_field).unwrap_or_else(|| {
panic!("Type parameters should only contain ids of generic types!")
});
utils::ident(&name)
})
.collect()
}
#[cfg(test)]
mod tests {
use fuel_abi_types::{
abi::unified_program::UnifiedTypeDeclaration, utils::extract_custom_type_name,
};
use pretty_assertions::assert_eq;
use super::*;
use crate::error::Result;
#[test]
fn extracts_generic_types() -> Result<()> {
// given
let declaration = UnifiedTypeDeclaration {
type_id: 0,
type_field: "".to_string(),
components: None,
type_parameters: Some(vec![1, 2]),
alias_of: None,
};
let generic_1 = UnifiedTypeDeclaration {
type_id: 1,
type_field: "generic T".to_string(),
components: None,
type_parameters: None,
alias_of: None,
};
let generic_2 = UnifiedTypeDeclaration {
type_id: 2,
type_field: "generic K".to_string(),
components: None,
type_parameters: None,
alias_of: None,
};
let types = [generic_1, generic_2]
.map(|decl| (decl.type_id, decl))
.into_iter()
.collect();
// when
let generics = extract_generic_parameters(&FullTypeDeclaration::from_counterpart(
&declaration,
&types,
));
// then
let stringified_generics = generics
.into_iter()
.map(|generic| generic.to_string())
.collect::<Vec<_>>();
assert_eq!(stringified_generics, vec!["T", "K"]);
Ok(())
}
#[test]
fn can_extract_struct_name() {
let declaration = UnifiedTypeDeclaration {
type_id: 0,
type_field: "struct SomeName".to_string(),
components: None,
type_parameters: None,
alias_of: None,
};
let struct_name = extract_custom_type_name(&declaration.type_field).unwrap();
assert_eq!(struct_name, "SomeName");
}
#[test]
fn can_extract_enum_name() {
let declaration = UnifiedTypeDeclaration {
type_id: 0,
type_field: "enum SomeEnumName".to_string(),
components: None,
type_parameters: None,
alias_of: None,
};
let struct_name = extract_custom_type_name(&declaration.type_field).unwrap();
assert_eq!(struct_name, "SomeEnumName");
}
}
| rust | Apache-2.0 | 865e00c295de8b4a0a1ef7ac926c3c8266d5151b | 2026-01-04T15:31:59.450823Z | false |
FuelLabs/fuels-rs | https://github.com/FuelLabs/fuels-rs/blob/865e00c295de8b4a0a1ef7ac926c3c8266d5151b/packages/fuels-macros/src/lib.rs | packages/fuels-macros/src/lib.rs | use fuels_code_gen::Abigen;
use proc_macro::TokenStream;
use syn::{DeriveInput, parse_macro_input};
use crate::{
abigen::MacroAbigenTargets,
derive::{
parameterize::generate_parameterize_impl, tokenizable::generate_tokenizable_impl,
try_from::generate_try_from_impl,
},
setup_program_test::{TestProgramCommands, generate_setup_program_test_code},
};
mod abigen;
mod derive;
mod parse_utils;
mod setup_program_test;
/// Used to generate bindings for Contracts, Scripts and Predicates. Accepts
/// input in the form of `ProgramType(name="MyBindings", abi=ABI_SOURCE)...`
///
/// `ProgramType` is either `Contract`, `Script` or `Predicate`.
///
/// `ABI_SOURCE` is a string literal representing either a path to the JSON ABI
/// file or the contents of the JSON ABI file itself.
///
///```text
/// abigen!(Contract(
/// name = "MyContract",
/// abi = "packages/fuels/tests/contracts/token_ops/out/release/token_ops-abi.json"
/// ));
///```
///
/// More details can be found in the [`Fuel Rust SDK Book`](https://fuellabs.github.io/fuels-rs/latest)
#[proc_macro]
pub fn abigen(input: TokenStream) -> TokenStream {
let targets = parse_macro_input!(input as MacroAbigenTargets);
Abigen::generate(targets.into(), false)
.expect("abigen generation failed")
.into()
}
#[proc_macro]
pub fn wasm_abigen(input: TokenStream) -> TokenStream {
let targets = parse_macro_input!(input as MacroAbigenTargets);
Abigen::generate(targets.into(), true)
.expect("abigen generation failed")
.into()
}
/// Used to reduce boilerplate in integration tests.
///
/// More details can be found in the [`Fuel Rust SDK Book`](https://fuellabs.github.io/fuels-rs/latest)
#[proc_macro]
pub fn setup_program_test(input: TokenStream) -> TokenStream {
let test_program_commands = parse_macro_input!(input as TestProgramCommands);
generate_setup_program_test_code(test_program_commands)
.unwrap_or_else(|e| e.to_compile_error())
.into()
}
#[proc_macro_derive(Parameterize, attributes(FuelsTypesPath, FuelsCorePath, NoStd, Ignore))]
pub fn parameterize(stream: TokenStream) -> TokenStream {
let input = parse_macro_input!(stream as DeriveInput);
generate_parameterize_impl(input)
.unwrap_or_else(|e| e.to_compile_error())
.into()
}
#[proc_macro_derive(Tokenizable, attributes(FuelsTypesPath, FuelsCorePath, NoStd, Ignore))]
pub fn tokenizable(stream: TokenStream) -> TokenStream {
let input = parse_macro_input!(stream as DeriveInput);
generate_tokenizable_impl(input)
.unwrap_or_else(|e| e.to_compile_error())
.into()
}
#[proc_macro_derive(TryFrom, attributes(FuelsTypesPath, FuelsCorePath, NoStd))]
pub fn try_from(stream: TokenStream) -> TokenStream {
let input = parse_macro_input!(stream as DeriveInput);
generate_try_from_impl(input)
.unwrap_or_else(|e| e.to_compile_error())
.into()
}
| rust | Apache-2.0 | 865e00c295de8b4a0a1ef7ac926c3c8266d5151b | 2026-01-04T15:31:59.450823Z | false |
FuelLabs/fuels-rs | https://github.com/FuelLabs/fuels-rs/blob/865e00c295de8b4a0a1ef7ac926c3c8266d5151b/packages/fuels-macros/src/parse_utils.rs | packages/fuels-macros/src/parse_utils.rs | pub(crate) use command::Command;
use itertools::{Itertools, chain};
use proc_macro2::{Ident, TokenStream};
use quote::{ToTokens, quote};
use syn::{
Attribute, DataEnum, DataStruct, Error, Fields, GenericParam, Generics, TypeParam, Variant,
};
pub(crate) use unique_lit_strs::UniqueLitStrs;
pub(crate) use unique_name_values::UniqueNameValues;
mod command;
mod unique_lit_strs;
mod unique_name_values;
pub(crate) trait ErrorsExt: Iterator<Item = Error> + Sized {
fn combine_errors(self) -> Option<Self::Item>;
fn validate_no_errors(self) -> Result<(), Self::Item>;
}
impl<T> ErrorsExt for T
where
T: Iterator<Item = Error> + Sized,
{
fn combine_errors(self) -> Option<Self::Item> {
self.reduce(|mut errors, error| {
errors.combine(error);
errors
})
}
fn validate_no_errors(self) -> Result<(), Self::Item> {
if let Some(err) = self.combine_errors() {
Err(err)
} else {
Ok(())
}
}
}
fn generate_duplicate_error<T>(duplicates: &[&T]) -> Error
where
T: ToTokens,
{
let mut iter = duplicates.iter();
let original_error = iter
.next()
.map(|first_el| Error::new_spanned(first_el, "original defined here:"));
let the_rest = iter.map(|duplicate| Error::new_spanned(duplicate, "duplicate!"));
chain!(original_error, the_rest)
.combine_errors()
.expect("has to be at least one error!")
}
fn group_up_duplicates<T, K, KeyFn>(name_values: &[T], key: KeyFn) -> Vec<Vec<&T>>
where
KeyFn: Fn(&&T) -> K,
K: Ord,
{
name_values
.iter()
.sorted_by_key(&key)
.group_by(&key)
.into_iter()
.filter_map(|(_, group)| {
let group = group.collect::<Vec<_>>();
(group.len() > 1).then_some(group)
})
.collect()
}
fn validate_no_duplicates<T, K, KeyFn>(elements: &[T], key_fn: KeyFn) -> syn::Result<()>
where
KeyFn: Fn(&&T) -> K + Copy,
T: ToTokens,
K: Ord,
{
group_up_duplicates(elements, key_fn)
.into_iter()
.map(|duplicates| generate_duplicate_error(&duplicates))
.validate_no_errors()
}
pub fn validate_and_extract_generic_types(generics: &Generics) -> syn::Result<Vec<&TypeParam>> {
generics
.params
.iter()
.map(|generic_param| match generic_param {
GenericParam::Type(generic_type) => Ok(generic_type),
GenericParam::Lifetime(lifetime) => {
Err(Error::new_spanned(lifetime, "Lifetimes not supported"))
}
GenericParam::Const(const_generic) => Err(Error::new_spanned(
const_generic,
"Const generics not supported",
)),
})
.collect()
}
enum Member {
Normal { name: Ident, ty: TokenStream },
Ignored { name: Ident },
}
pub(crate) struct Members {
members: Vec<Member>,
fuels_core_path: TokenStream,
}
impl Members {
pub(crate) fn from_struct(
fields: DataStruct,
fuels_core_path: TokenStream,
) -> syn::Result<Self> {
let named_fields = match fields.fields {
Fields::Named(named_fields) => Ok(named_fields.named),
Fields::Unnamed(fields) => Err(Error::new_spanned(
fields.unnamed,
"Tuple-like structs not supported",
)),
_ => {
panic!("This cannot happen in valid Rust code. Fields::Unit only appears in enums")
}
}?;
let members = named_fields
.into_iter()
.map(|field| {
let name = field
.ident
.expect("`FieldsNamed` to only contain named fields");
if has_ignore_attr(&field.attrs) {
Member::Ignored { name }
} else {
let ty = field.ty.into_token_stream();
Member::Normal { name, ty }
}
})
.collect();
Ok(Members {
members,
fuels_core_path,
})
}
pub(crate) fn from_enum(data: DataEnum, fuels_core_path: TokenStream) -> syn::Result<Self> {
let members = data
.variants
.into_iter()
.map(|variant: Variant| {
let name = variant.ident;
if has_ignore_attr(&variant.attrs) {
Ok(Member::Ignored { name })
} else {
let ty = match variant.fields {
Fields::Unnamed(fields_unnamed) => {
if fields_unnamed.unnamed.len() != 1 {
return Err(Error::new(
fields_unnamed.paren_token.span.join(),
"must have exactly one element",
));
}
fields_unnamed.unnamed.into_iter().next()
}
Fields::Unit => None,
Fields::Named(named_fields) => {
return Err(Error::new_spanned(
named_fields,
"struct-like enum variants are not supported",
));
}
}
.map(|field| field.ty.into_token_stream())
.unwrap_or_else(|| quote! {()});
Ok(Member::Normal { name, ty })
}
})
.collect::<Result<Vec<_>, _>>()?;
Ok(Members {
members,
fuels_core_path,
})
}
pub(crate) fn names(&self) -> impl Iterator<Item = &Ident> + '_ {
self.members.iter().filter_map(|member| {
if let Member::Normal { name, .. } = member {
Some(name)
} else {
None
}
})
}
pub(crate) fn names_as_strings(&self) -> impl Iterator<Item = TokenStream> + '_ {
self.names().map(|ident| {
let name = ident.to_string();
quote! {#name.to_string()}
})
}
pub(crate) fn ignored_names(&self) -> impl Iterator<Item = &Ident> + '_ {
self.members.iter().filter_map(|member| {
if let Member::Ignored { name } = member {
Some(name)
} else {
None
}
})
}
pub(crate) fn param_type_calls(&self) -> impl Iterator<Item = TokenStream> + '_ {
let fuels_core_path = self.fuels_core_path.to_token_stream();
self.members.iter().filter_map(move |member| match member {
Member::Normal { ty, .. } => {
Some(quote! { <#ty as #fuels_core_path::traits::Parameterize>::param_type() })
}
_ => None,
})
}
}
pub(crate) fn has_ignore_attr(attrs: &[Attribute]) -> bool {
attrs.iter().any(|attr| match &attr.meta {
syn::Meta::Path(path) => path.get_ident().is_some_and(|ident| ident == "Ignore"),
_ => false,
})
}
| rust | Apache-2.0 | 865e00c295de8b4a0a1ef7ac926c3c8266d5151b | 2026-01-04T15:31:59.450823Z | false |
FuelLabs/fuels-rs | https://github.com/FuelLabs/fuels-rs/blob/865e00c295de8b4a0a1ef7ac926c3c8266d5151b/packages/fuels-macros/src/setup_program_test.rs | packages/fuels-macros/src/setup_program_test.rs | pub(crate) use code_gen::generate_setup_program_test_code;
pub(crate) use parsing::TestProgramCommands;
mod code_gen;
mod parsing;
| rust | Apache-2.0 | 865e00c295de8b4a0a1ef7ac926c3c8266d5151b | 2026-01-04T15:31:59.450823Z | false |
FuelLabs/fuels-rs | https://github.com/FuelLabs/fuels-rs/blob/865e00c295de8b4a0a1ef7ac926c3c8266d5151b/packages/fuels-macros/src/derive.rs | packages/fuels-macros/src/derive.rs | pub mod parameterize;
pub mod tokenizable;
pub mod try_from;
mod utils;
| rust | Apache-2.0 | 865e00c295de8b4a0a1ef7ac926c3c8266d5151b | 2026-01-04T15:31:59.450823Z | false |
FuelLabs/fuels-rs | https://github.com/FuelLabs/fuels-rs/blob/865e00c295de8b4a0a1ef7ac926c3c8266d5151b/packages/fuels-macros/src/abigen.rs | packages/fuels-macros/src/abigen.rs | pub(crate) use parsing::MacroAbigenTargets;
mod parsing;
| rust | Apache-2.0 | 865e00c295de8b4a0a1ef7ac926c3c8266d5151b | 2026-01-04T15:31:59.450823Z | false |
FuelLabs/fuels-rs | https://github.com/FuelLabs/fuels-rs/blob/865e00c295de8b4a0a1ef7ac926c3c8266d5151b/packages/fuels-macros/src/setup_program_test/code_gen.rs | packages/fuels-macros/src/setup_program_test/code_gen.rs | use std::{
collections::HashMap,
path::{Path, PathBuf},
};
use fuels_code_gen::{Abi, Abigen, AbigenTarget, ProgramType, utils::ident};
use proc_macro2::{Ident, Span, TokenStream};
use quote::quote;
use syn::LitStr;
use crate::setup_program_test::parsing::{
AbigenCommand, BuildProfile, DeployContractCommand, InitializeWalletCommand, LoadScriptCommand,
SetOptionsCommand, TestProgramCommands,
};
pub(crate) fn generate_setup_program_test_code(
commands: TestProgramCommands,
) -> syn::Result<TokenStream> {
let TestProgramCommands {
set_options,
initialize_wallets,
generate_bindings,
deploy_contract,
load_scripts,
} = commands;
let SetOptionsCommand { profile } = set_options.unwrap_or_default();
let project_lookup = generate_project_lookup(&generate_bindings, profile)?;
let abigen_code = abigen_code(&project_lookup)?;
let wallet_code = wallet_initialization_code(initialize_wallets);
let deploy_code = contract_deploying_code(&deploy_contract, &project_lookup);
let script_code = script_loading_code(&load_scripts, &project_lookup);
Ok(quote! {
#abigen_code
#wallet_code
#deploy_code
#script_code
})
}
fn generate_project_lookup(
commands: &AbigenCommand,
profile: BuildProfile,
) -> syn::Result<HashMap<String, Project>> {
let pairs = commands
.targets
.iter()
.map(|command| -> syn::Result<_> {
let project = Project::new(command.program_type, &command.project, profile.clone())?;
Ok((command.name.value(), project))
})
.collect::<Result<Vec<_>, _>>()?;
Ok(pairs.into_iter().collect())
}
fn abigen_code(project_lookup: &HashMap<String, Project>) -> syn::Result<TokenStream> {
let targets = parse_abigen_targets(project_lookup)?;
Ok(Abigen::generate(targets, false).expect("abigen generation failed"))
}
fn parse_abigen_targets(
project_lookup: &HashMap<String, Project>,
) -> syn::Result<Vec<AbigenTarget>> {
project_lookup
.iter()
.map(|(name, project)| {
let source = Abi::load_from(project.abi_path())
.map_err(|e| syn::Error::new(project.path_span, e.to_string()))?;
Ok(AbigenTarget::new(
name.clone(),
source,
project.program_type,
))
})
.collect()
}
fn wallet_initialization_code(maybe_command: Option<InitializeWalletCommand>) -> TokenStream {
let command = if let Some(command) = maybe_command {
command
} else {
return Default::default();
};
let wallet_names = extract_wallet_names(&command);
if wallet_names.is_empty() {
return Default::default();
}
let num_wallets = wallet_names.len();
quote! {
let [#(#wallet_names),*]: [_; #num_wallets] = ::fuels::test_helpers::launch_custom_provider_and_get_wallets(
::fuels::test_helpers::WalletsConfig::new(Some(#num_wallets as u64), None, None),
None,
None,
)
.await
.expect("Error while trying to fetch wallets from the custom provider")
.try_into()
.expect("Should have the exact number of wallets");
}
}
fn extract_wallet_names(command: &InitializeWalletCommand) -> Vec<Ident> {
command
.names
.iter()
.map(|name| ident(&name.value()))
.collect()
}
fn contract_deploying_code(
commands: &[DeployContractCommand],
project_lookup: &HashMap<String, Project>,
) -> TokenStream {
commands
.iter()
.map(|command| {
let contract_instance_name = ident(&command.name);
let contract_struct_name = ident(&command.contract.value());
let wallet_name = ident(&command.wallet);
let random_salt = command.random_salt;
let project = project_lookup
.get(&command.contract.value())
.expect("Project should be in lookup");
let bin_path = project.bin_path();
let salt = if random_salt {
quote! {
// Generate random salt for contract deployment.
// These lines must be inside the `quote!` macro, otherwise the salt remains
// identical between macro compilation, causing contract id collision.
::fuels::test_helpers::generate_random_salt()
}
} else {
quote! { [0; 32] }
};
quote! {
let salt: [u8; 32] = #salt;
let #contract_instance_name = {
let load_config = ::fuels::programs::contract::LoadConfiguration::default().with_salt(salt);
let loaded_contract = ::fuels::programs::contract::Contract::load_from(
#bin_path,
load_config
)
.expect("Failed to load the contract");
let response = loaded_contract.deploy_if_not_exists(
&#wallet_name,
::fuels::types::transaction::TxPolicies::default()
)
.await
.expect("Failed to deploy the contract");
#contract_struct_name::new(response.contract_id, #wallet_name.clone())
};
}
})
.reduce(|mut all_code, code| {
all_code.extend(code);
all_code
})
.unwrap_or_default()
}
fn script_loading_code(
commands: &[LoadScriptCommand],
project_lookup: &HashMap<String, Project>,
) -> TokenStream {
commands
.iter()
.map(|command| {
let script_instance_name = ident(&command.name);
let script_struct_name = ident(&command.script.value());
let wallet_name = ident(&command.wallet);
let project = project_lookup
.get(&command.script.value())
.expect("Project should be in lookup");
let bin_path = project.bin_path();
quote! {
let #script_instance_name = #script_struct_name::new(#wallet_name.clone(), #bin_path);
}
})
.reduce(|mut all_code, code| {
all_code.extend(code);
all_code
})
.unwrap_or_default()
}
struct Project {
program_type: ProgramType,
path: PathBuf,
path_span: Span,
profile: BuildProfile,
}
impl Project {
fn new(program_type: ProgramType, dir: &LitStr, profile: BuildProfile) -> syn::Result<Self> {
let path = Path::new(&dir.value()).canonicalize().map_err(|_| {
syn::Error::new_spanned(
dir.clone(),
"unable to canonicalize forc project path. Make sure the path is valid!",
)
})?;
Ok(Self {
program_type,
path,
path_span: dir.span(),
profile,
})
}
fn compile_file_path(&self, suffix: &str, description: &str) -> String {
self.path
.join(
[
format!("out/{}/", &self.profile).as_str(),
self.project_name(),
suffix,
]
.concat(),
)
.to_str()
.unwrap_or_else(|| panic!("could not join path for {description}"))
.to_string()
}
fn project_name(&self) -> &str {
self.path
.file_name()
.expect("failed to get project name")
.to_str()
.expect("failed to convert project name to string")
}
fn abi_path(&self) -> String {
self.compile_file_path("-abi.json", "the ABI file")
}
fn bin_path(&self) -> String {
self.compile_file_path(".bin", "the binary file")
}
}
| rust | Apache-2.0 | 865e00c295de8b4a0a1ef7ac926c3c8266d5151b | 2026-01-04T15:31:59.450823Z | false |
FuelLabs/fuels-rs | https://github.com/FuelLabs/fuels-rs/blob/865e00c295de8b4a0a1ef7ac926c3c8266d5151b/packages/fuels-macros/src/setup_program_test/parsing.rs | packages/fuels-macros/src/setup_program_test/parsing.rs | pub(crate) use commands::{
AbigenCommand, BuildProfile, DeployContractCommand, InitializeWalletCommand, LoadScriptCommand,
SetOptionsCommand, TestProgramCommands,
};
mod command_parser;
mod commands;
mod validations;
| rust | Apache-2.0 | 865e00c295de8b4a0a1ef7ac926c3c8266d5151b | 2026-01-04T15:31:59.450823Z | false |
FuelLabs/fuels-rs | https://github.com/FuelLabs/fuels-rs/blob/865e00c295de8b4a0a1ef7ac926c3c8266d5151b/packages/fuels-macros/src/setup_program_test/parsing/command_parser.rs | packages/fuels-macros/src/setup_program_test/parsing/command_parser.rs | macro_rules! command_parser {
($($command_name: ident -> $command_struct: ty),+ $(,)?) => {
#[derive(Default)]
#[allow(non_snake_case)]
pub(crate) struct CommandParser {
$(pub(crate) $command_name: Vec<$command_struct>),*
}
impl CommandParser {
fn available_commands() -> impl Iterator<Item=&'static str> {
[$(stringify!($command_name)),*].into_iter()
}
pub(crate) fn parse_and_save(&mut self, command: $crate::parse_utils::Command) -> ::syn::Result<()>{
match command.name.to_string().as_str() {
$(stringify!($command_name) => self.$command_name.push(command.try_into()?),)*
_ => {
let msg = Self::available_commands().map(|command| format!("'{command}'")).join(", ");
return Err(::syn::Error::new(command.name.span(), format!("Unrecognized command. Expected one of: {msg}")));
}
};
Ok(())
}
}
impl Parse for CommandParser {
fn parse(input: ::syn::parse::ParseStream) -> Result<Self> {
use $crate::parse_utils::ErrorsExt;
let mut command_parser = Self::default();
let mut errors = vec![];
for command in $crate::parse_utils::Command::parse_multiple(input)? {
if let Err(error) = command_parser.parse_and_save(command) {
errors.push(error);
}
}
errors.into_iter().validate_no_errors()?;
Ok(command_parser)
}
}
}
}
pub(crate) use command_parser;
| rust | Apache-2.0 | 865e00c295de8b4a0a1ef7ac926c3c8266d5151b | 2026-01-04T15:31:59.450823Z | false |
FuelLabs/fuels-rs | https://github.com/FuelLabs/fuels-rs/blob/865e00c295de8b4a0a1ef7ac926c3c8266d5151b/packages/fuels-macros/src/setup_program_test/parsing/commands.rs | packages/fuels-macros/src/setup_program_test/parsing/commands.rs | pub(crate) use abigen::AbigenCommand;
pub(crate) use deploy_contract::DeployContractCommand;
pub(crate) use initialize_wallet::InitializeWalletCommand;
use itertools::Itertools;
pub(crate) use load_script::LoadScriptCommand;
pub(crate) use set_options::{BuildProfile, SetOptionsCommand};
use syn::{
Result,
parse::{Parse, ParseStream},
};
use crate::setup_program_test::parsing::{
command_parser::command_parser,
validations::{
extract_the_abigen_command, validate_all_contracts_are_known,
validate_all_scripts_are_known, validate_zero_or_one_wallet_command_present,
},
};
mod abigen;
mod deploy_contract;
mod initialize_wallet;
mod load_script;
mod set_options;
// Contains the result of parsing the input to the `setup_program_test` macro.
// Contents represent the users wishes with regards to wallet initialization,
// bindings generation and contract deployment.
pub(crate) struct TestProgramCommands {
pub(crate) set_options: Option<SetOptionsCommand>,
pub(crate) initialize_wallets: Option<InitializeWalletCommand>,
pub(crate) generate_bindings: AbigenCommand,
pub(crate) deploy_contract: Vec<DeployContractCommand>,
pub(crate) load_scripts: Vec<LoadScriptCommand>,
}
command_parser!(
Options -> SetOptionsCommand,
Wallets -> InitializeWalletCommand,
Abigen -> AbigenCommand,
Deploy -> DeployContractCommand,
LoadScript -> LoadScriptCommand
);
impl Parse for TestProgramCommands {
fn parse(input: ParseStream) -> Result<Self> {
let span = input.span();
let mut parsed_commands = CommandParser::parse(input)?;
let abigen_command = extract_the_abigen_command(span, &parsed_commands.Abigen)?;
validate_all_contracts_are_known(&abigen_command, &parsed_commands.Deploy)?;
validate_all_scripts_are_known(&abigen_command, &parsed_commands.LoadScript)?;
validate_zero_or_one_wallet_command_present(&parsed_commands.Wallets)?;
Ok(Self {
set_options: parsed_commands.Options.pop(),
initialize_wallets: parsed_commands.Wallets.pop(),
generate_bindings: abigen_command,
deploy_contract: parsed_commands.Deploy,
load_scripts: parsed_commands.LoadScript,
})
}
}
| rust | Apache-2.0 | 865e00c295de8b4a0a1ef7ac926c3c8266d5151b | 2026-01-04T15:31:59.450823Z | false |
FuelLabs/fuels-rs | https://github.com/FuelLabs/fuels-rs/blob/865e00c295de8b4a0a1ef7ac926c3c8266d5151b/packages/fuels-macros/src/setup_program_test/parsing/validations.rs | packages/fuels-macros/src/setup_program_test/parsing/validations.rs | use std::collections::HashSet;
use fuels_code_gen::ProgramType;
use proc_macro2::Span;
use syn::{Error, LitStr, Result};
use crate::{
parse_utils::ErrorsExt,
setup_program_test::parsing::{
AbigenCommand, DeployContractCommand, InitializeWalletCommand, LoadScriptCommand,
},
};
pub(crate) fn extract_the_abigen_command(
parent_span: Span,
abigen_commands: &[AbigenCommand],
) -> Result<AbigenCommand> {
match abigen_commands {
[single_command] => Ok(single_command.clone()),
commands => {
let err = commands
.iter()
.map(|command| Error::new(command.span, "Only one `Abigen` command allowed"))
.combine_errors()
.unwrap_or_else(|| Error::new(parent_span, "Add an `Abigen(..)` command!"));
Err(err)
}
}
}
pub(crate) fn validate_all_contracts_are_known(
abigen_command: &AbigenCommand,
deploy_commands: &[DeployContractCommand],
) -> Result<()> {
extract_contracts_to_deploy(deploy_commands)
.difference(&names_of_program_bindings(
abigen_command,
ProgramType::Contract,
))
.flat_map(|unknown_contract| {
[
Error::new_spanned(unknown_contract, "Contract is unknown"),
Error::new(
abigen_command.span,
format!(
"Consider adding: Contract(name=\"{}\", project=...)",
unknown_contract.value()
),
),
]
})
.validate_no_errors()
}
pub(crate) fn validate_all_scripts_are_known(
abigen_command: &AbigenCommand,
load_commands: &[LoadScriptCommand],
) -> Result<()> {
extract_scripts_to_load(load_commands)
.difference(&names_of_program_bindings(
abigen_command,
ProgramType::Script,
))
.flat_map(|unknown_contract| {
[
Error::new_spanned(unknown_contract, "Script is unknown"),
Error::new(
abigen_command.span,
format!(
"Consider adding: Script(name=\"{}\", project=...)",
unknown_contract.value()
),
),
]
})
.validate_no_errors()
}
pub(crate) fn validate_zero_or_one_wallet_command_present(
commands: &[InitializeWalletCommand],
) -> Result<()> {
if commands.len() > 1 {
commands
.iter()
.map(|command| Error::new(command.span, "Only one `Wallets` command allowed"))
.combine_errors()
.map(Err)
.expect("Known to have at least one error")
} else {
Ok(())
}
}
fn names_of_program_bindings(
commands: &AbigenCommand,
program_type: ProgramType,
) -> HashSet<&LitStr> {
commands
.targets
.iter()
.filter_map(|target| (target.program_type == program_type).then_some(&target.name))
.collect()
}
fn extract_contracts_to_deploy(commands: &[DeployContractCommand]) -> HashSet<&LitStr> {
commands.iter().map(|c| &c.contract).collect()
}
fn extract_scripts_to_load(commands: &[LoadScriptCommand]) -> HashSet<&LitStr> {
commands.iter().map(|c| &c.script).collect()
}
| rust | Apache-2.0 | 865e00c295de8b4a0a1ef7ac926c3c8266d5151b | 2026-01-04T15:31:59.450823Z | false |
FuelLabs/fuels-rs | https://github.com/FuelLabs/fuels-rs/blob/865e00c295de8b4a0a1ef7ac926c3c8266d5151b/packages/fuels-macros/src/setup_program_test/parsing/commands/initialize_wallet.rs | packages/fuels-macros/src/setup_program_test/parsing/commands/initialize_wallet.rs | use std::convert::TryFrom;
use proc_macro2::Span;
use syn::{Error, LitStr};
use crate::parse_utils::{Command, UniqueLitStrs};
#[derive(Debug, Clone)]
pub struct InitializeWalletCommand {
pub span: Span,
pub names: Vec<LitStr>,
}
impl TryFrom<Command> for InitializeWalletCommand {
type Error = Error;
fn try_from(command: Command) -> Result<Self, Self::Error> {
let wallets = UniqueLitStrs::new(command.contents)?;
Ok(Self {
span: command.name.span(),
names: wallets.into_iter().collect(),
})
}
}
| rust | Apache-2.0 | 865e00c295de8b4a0a1ef7ac926c3c8266d5151b | 2026-01-04T15:31:59.450823Z | false |
FuelLabs/fuels-rs | https://github.com/FuelLabs/fuels-rs/blob/865e00c295de8b4a0a1ef7ac926c3c8266d5151b/packages/fuels-macros/src/setup_program_test/parsing/commands/abigen.rs | packages/fuels-macros/src/setup_program_test/parsing/commands/abigen.rs | use std::convert::TryFrom;
use fuels_code_gen::ProgramType;
use proc_macro2::Span;
use syn::{Error, LitStr};
use crate::parse_utils::{Command, UniqueNameValues};
#[derive(Debug, Clone)]
pub(crate) struct TargetInfo {
pub(crate) name: LitStr,
pub(crate) project: LitStr,
pub(crate) program_type: ProgramType,
}
impl TryFrom<Command> for TargetInfo {
type Error = Error;
fn try_from(command: Command) -> Result<Self, Self::Error> {
let program_type = command.name.try_into()?;
let name_values = UniqueNameValues::new(command.contents)?;
name_values.validate_has_no_other_names(&["name", "project"])?;
let name = name_values.get_as_lit_str("name")?.clone();
let project = name_values.get_as_lit_str("project")?.clone();
Ok(Self {
name,
project,
program_type,
})
}
}
#[derive(Debug, Clone)]
pub(crate) struct AbigenCommand {
pub(crate) span: Span,
pub(crate) targets: Vec<TargetInfo>,
}
impl TryFrom<Command> for AbigenCommand {
type Error = Error;
fn try_from(command: Command) -> Result<Self, Self::Error> {
let span = command.name.span();
let targets = command
.parse_nested_metas()?
.into_iter()
.map(|meta| Command::new(meta).and_then(TargetInfo::try_from))
.collect::<Result<Vec<_>, _>>()?;
Ok(Self { span, targets })
}
}
| rust | Apache-2.0 | 865e00c295de8b4a0a1ef7ac926c3c8266d5151b | 2026-01-04T15:31:59.450823Z | false |
FuelLabs/fuels-rs | https://github.com/FuelLabs/fuels-rs/blob/865e00c295de8b4a0a1ef7ac926c3c8266d5151b/packages/fuels-macros/src/setup_program_test/parsing/commands/load_script.rs | packages/fuels-macros/src/setup_program_test/parsing/commands/load_script.rs | use std::convert::TryFrom;
use syn::{Error, LitStr};
use crate::parse_utils::{Command, UniqueNameValues};
#[derive(Debug, Clone)]
pub struct LoadScriptCommand {
pub name: String,
pub script: LitStr,
pub wallet: String,
}
impl TryFrom<Command> for LoadScriptCommand {
type Error = Error;
fn try_from(command: Command) -> Result<Self, Self::Error> {
let name_values = UniqueNameValues::new(command.contents)?;
name_values.validate_has_no_other_names(&["name", "script", "wallet"])?;
let name = name_values.get_as_lit_str("name")?.value();
let script = name_values.get_as_lit_str("script")?.clone();
let wallet = name_values.get_as_lit_str("wallet")?.value();
Ok(Self {
name,
script,
wallet,
})
}
}
| rust | Apache-2.0 | 865e00c295de8b4a0a1ef7ac926c3c8266d5151b | 2026-01-04T15:31:59.450823Z | false |
FuelLabs/fuels-rs | https://github.com/FuelLabs/fuels-rs/blob/865e00c295de8b4a0a1ef7ac926c3c8266d5151b/packages/fuels-macros/src/setup_program_test/parsing/commands/set_options.rs | packages/fuels-macros/src/setup_program_test/parsing/commands/set_options.rs | use std::{convert::TryFrom, fmt, str::FromStr};
use syn::Error;
use crate::parse_utils::{Command, UniqueNameValues};
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub enum BuildProfile {
Debug,
#[default]
Release,
}
impl FromStr for BuildProfile {
type Err = &'static str;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
"debug" => Ok(Self::Debug),
"release" => Ok(Self::Release),
_ => Err(r#"invalid build profile option: must be "debug" or "release""#),
}
}
}
impl fmt::Display for BuildProfile {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"{}",
match self {
BuildProfile::Debug => "debug",
BuildProfile::Release => "release",
}
)
}
}
#[derive(Debug, Clone, Default)]
pub struct SetOptionsCommand {
pub profile: BuildProfile,
}
impl TryFrom<Command> for SetOptionsCommand {
type Error = Error;
fn try_from(command: Command) -> Result<Self, Self::Error> {
let name_values = UniqueNameValues::new(command.contents)?;
name_values.validate_has_no_other_names(&["profile"])?;
let profile = name_values.get_as_lit_str("profile")?;
let profile = profile
.value()
.as_str()
.parse()
.map_err(|msg| Error::new(profile.span(), msg))?;
Ok(Self { profile })
}
}
| rust | Apache-2.0 | 865e00c295de8b4a0a1ef7ac926c3c8266d5151b | 2026-01-04T15:31:59.450823Z | false |
FuelLabs/fuels-rs | https://github.com/FuelLabs/fuels-rs/blob/865e00c295de8b4a0a1ef7ac926c3c8266d5151b/packages/fuels-macros/src/setup_program_test/parsing/commands/deploy_contract.rs | packages/fuels-macros/src/setup_program_test/parsing/commands/deploy_contract.rs | use std::convert::TryFrom;
use syn::{Error, Lit, LitStr};
use crate::parse_utils::{Command, UniqueNameValues};
#[derive(Debug, Clone)]
pub struct DeployContractCommand {
pub name: String,
pub contract: LitStr,
pub wallet: String,
pub random_salt: bool,
}
impl TryFrom<Command> for DeployContractCommand {
type Error = Error;
fn try_from(command: Command) -> Result<Self, Self::Error> {
let name_values = UniqueNameValues::new(command.contents)?;
name_values.validate_has_no_other_names(&["name", "contract", "wallet", "random_salt"])?;
let name = name_values.get_as_lit_str("name")?.value();
let contract = name_values.get_as_lit_str("contract")?.clone();
let wallet = name_values.get_as_lit_str("wallet")?.value();
let random_salt = name_values.try_get("random_salt").is_none_or(|opt| {
let Lit::Bool(b) = opt else { return true };
b.value()
});
Ok(Self {
name,
contract,
wallet,
random_salt,
})
}
}
| rust | Apache-2.0 | 865e00c295de8b4a0a1ef7ac926c3c8266d5151b | 2026-01-04T15:31:59.450823Z | false |
FuelLabs/fuels-rs | https://github.com/FuelLabs/fuels-rs/blob/865e00c295de8b4a0a1ef7ac926c3c8266d5151b/packages/fuels-macros/src/parse_utils/unique_lit_strs.rs | packages/fuels-macros/src/parse_utils/unique_lit_strs.rs | use std::vec::IntoIter;
use proc_macro2::{Span, TokenStream};
use syn::{LitStr, Result, parse::Parser, punctuated::Punctuated, spanned::Spanned, token::Comma};
use crate::parse_utils::validate_no_duplicates;
#[derive(Debug)]
pub struct UniqueLitStrs {
span: Span,
lit_strs: Vec<LitStr>,
}
impl UniqueLitStrs {
pub fn new(tokens: TokenStream) -> Result<Self> {
let parsed_lit_strs = Punctuated::<LitStr, Comma>::parse_terminated.parse2(tokens)?;
let span = parsed_lit_strs.span();
let lit_strs: Vec<_> = parsed_lit_strs.into_iter().collect();
validate_no_duplicates(&lit_strs, |ls| ls.value())?;
Ok(Self { span, lit_strs })
}
#[allow(dead_code)]
pub fn iter(&self) -> impl Iterator<Item = &LitStr> {
self.lit_strs.iter()
}
#[allow(dead_code)]
pub fn span(&self) -> Span {
self.span
}
}
impl IntoIterator for UniqueLitStrs {
type Item = LitStr;
type IntoIter = IntoIter<Self::Item>;
fn into_iter(self) -> Self::IntoIter {
self.lit_strs.into_iter()
}
}
#[cfg(test)]
mod tests {
use proc_macro2::TokenStream;
use quote::quote;
use super::*;
use crate::parse_utils::Command;
#[test]
fn correctly_reads_lit_strs() -> Result<()> {
// given
let stream = quote! {SomeCommand("lit1", "lit2")};
// when
let unique_lit_strs = parse_unique_lit_strs(stream)?;
// then
let stringified = unique_lit_strs
.iter()
.map(|lit_str| lit_str.value())
.collect::<Vec<_>>();
assert_eq!(stringified, vec!["lit1", "lit2"]);
Ok(())
}
#[test]
fn doesnt_allow_duplicates() {
// given
let stream = quote! {SomeCommand("lit1", "lit2", "lit1")};
// when
let err = parse_unique_lit_strs(stream).expect_err("should have failed");
// then
let messages = err.into_iter().map(|e| e.to_string()).collect::<Vec<_>>();
assert_eq!(messages, vec!["original defined here:", "duplicate!"]);
}
#[test]
fn only_strings_allowed() {
let stream = quote! {SomeCommand("lit1", "lit2", true)};
let err = parse_unique_lit_strs(stream).expect_err("should have failed");
assert_eq!(err.to_string(), "expected string literal");
}
fn parse_unique_lit_strs(stream: TokenStream) -> Result<UniqueLitStrs> {
let command = Command::parse_single_from_token_stream(stream)?;
UniqueLitStrs::new(command.contents)
}
}
| rust | Apache-2.0 | 865e00c295de8b4a0a1ef7ac926c3c8266d5151b | 2026-01-04T15:31:59.450823Z | false |
FuelLabs/fuels-rs | https://github.com/FuelLabs/fuels-rs/blob/865e00c295de8b4a0a1ef7ac926c3c8266d5151b/packages/fuels-macros/src/parse_utils/command.rs | packages/fuels-macros/src/parse_utils/command.rs | use proc_macro2::{Ident, TokenStream};
use syn::{
Error, Meta,
Meta::List,
parse::{ParseStream, Parser},
punctuated::Punctuated,
token::Comma,
};
#[derive(Debug)]
pub struct Command {
pub name: Ident,
pub contents: TokenStream,
}
impl Command {
pub fn parse_multiple(input: ParseStream) -> syn::Result<Vec<Command>> {
input
.call(Punctuated::<Meta, Comma>::parse_terminated)?
.into_iter()
.map(Command::new)
.collect()
}
pub fn new(meta: Meta) -> syn::Result<Self> {
if let List(meta_list) = meta {
let name = meta_list.path.get_ident().cloned().ok_or_else(|| {
Error::new_spanned(
&meta_list.path,
"command name cannot be a Path -- i.e. contain ':'",
)
})?;
Ok(Self {
name,
contents: meta_list.tokens,
})
} else {
Err(Error::new_spanned(
meta,
"expected a command name literal -- e.g. `Something(...)`",
))
}
}
pub fn parse_nested_metas(self) -> syn::Result<Punctuated<Meta, Comma>> {
Punctuated::<Meta, Comma>::parse_terminated.parse2(self.contents)
}
#[cfg(test)]
pub(crate) fn parse_multiple_from_token_stream(
stream: proc_macro2::TokenStream,
) -> syn::Result<Vec<Self>> {
syn::parse::Parser::parse2(Command::parse_multiple, stream)
}
#[cfg(test)]
pub(crate) fn parse_single_from_token_stream(
stream: proc_macro2::TokenStream,
) -> syn::Result<Self> {
syn::parse::Parser::parse2(Command::parse_multiple, stream.clone())?
.pop()
.ok_or_else(|| Error::new_spanned(stream, "expected to have at least one command!"))
}
}
#[cfg(test)]
mod tests {
use quote::quote;
use crate::parse_utils::command::Command;
#[test]
fn command_name_is_properly_extracted() -> syn::Result<()> {
// given
let macro_contents = quote! {SomeCommand(), OtherCommand()};
// when
let commands = Command::parse_multiple_from_token_stream(macro_contents)?;
// then
let command_names = commands
.into_iter()
.map(|command| command.name.to_string())
.collect::<Vec<_>>();
assert_eq!(command_names, vec!["SomeCommand", "OtherCommand"]);
Ok(())
}
}
| rust | Apache-2.0 | 865e00c295de8b4a0a1ef7ac926c3c8266d5151b | 2026-01-04T15:31:59.450823Z | false |
FuelLabs/fuels-rs | https://github.com/FuelLabs/fuels-rs/blob/865e00c295de8b4a0a1ef7ac926c3c8266d5151b/packages/fuels-macros/src/parse_utils/unique_name_values.rs | packages/fuels-macros/src/parse_utils/unique_name_values.rs | use std::collections::HashMap;
use fuels_code_gen::utils::ident;
use itertools::Itertools;
use proc_macro2::{Ident, Span, TokenStream};
use syn::{
Error, Expr, Lit, LitStr, MetaNameValue, parse::Parser, punctuated::Punctuated,
spanned::Spanned,
};
use crate::parse_utils::{ErrorsExt, validate_no_duplicates};
#[derive(Debug)]
pub struct UniqueNameValues {
span: Span,
name_values: HashMap<Ident, Lit>,
}
impl UniqueNameValues {
pub fn new(tokens: TokenStream) -> syn::Result<Self> {
let name_value_metas = Punctuated::<MetaNameValue, syn::token::Comma>::parse_terminated
.parse2(tokens)
.map_err(|e| Error::new(e.span(), "expected name='value'"))?;
let span = name_value_metas.span();
let name_values = Self::extract_name_values(name_value_metas.into_iter())?;
let names = name_values.iter().map(|(name, _)| name).collect::<Vec<_>>();
validate_no_duplicates(&names, |&&name| name.clone())?;
Ok(Self {
span,
name_values: name_values.into_iter().collect(),
})
}
pub fn try_get(&self, name: &str) -> Option<&Lit> {
self.name_values.get(&ident(name))
}
pub fn validate_has_no_other_names(&self, allowed_names: &[&str]) -> syn::Result<()> {
let expected_names = allowed_names
.iter()
.map(|name| format!("'{name}'"))
.join(", ");
self.name_values
.keys()
.filter(|name| !allowed_names.contains(&name.to_string().as_str()))
.map(|name| {
Error::new_spanned(
name.clone(),
format!("attribute '{name}' not recognized. Expected one of: {expected_names}"),
)
})
.validate_no_errors()
}
pub fn get_as_lit_str(&self, name: &str) -> syn::Result<&LitStr> {
let value = self
.try_get(name)
.ok_or_else(|| Error::new(self.span, format!("missing attribute '{name}'")))?;
if let Lit::Str(lit_str) = value {
Ok(lit_str)
} else {
Err(Error::new_spanned(
value.clone(),
format!("expected the attribute '{name}' to have a string value"),
))
}
}
fn extract_name_values<T: Iterator<Item = MetaNameValue>>(
name_value_metas: T,
) -> syn::Result<Vec<(Ident, Lit)>> {
let (name_values, name_value_errors): (Vec<_>, Vec<Error>) = name_value_metas
.into_iter()
.map(|nv| {
let ident = nv.path.get_ident().cloned().ok_or_else(|| {
Error::new_spanned(
nv.path,
"attribute name cannot be a `Path` -- i.e. must not contain ':'",
)
})?;
let Expr::Lit(expr_lit) = nv.value else {
return Err(Error::new_spanned(nv.value, "expected literal"));
};
Ok((ident, expr_lit.lit))
})
.partition_result();
name_value_errors.into_iter().validate_no_errors()?;
Ok(name_values)
}
}
#[cfg(test)]
mod tests {
use proc_macro2::TokenStream;
use quote::quote;
use syn::LitBool;
use super::*;
use crate::parse_utils::command::Command;
#[test]
fn name_values_correctly_parsed() -> syn::Result<()> {
// given
let name_values = extract_name_values(quote! {SomeCommand(attr1="value1", attr2=true)})?;
// when
let attr_values = ["attr1", "attr2"].map(|attr| {
name_values
.try_get(attr)
.unwrap_or_else(|| panic!("attribute {attr} should have existed"))
.clone()
});
// then
let expected_values = [
Lit::Str(LitStr::new("value1", Span::call_site())),
Lit::Bool(LitBool::new(true, Span::call_site())),
];
assert_eq!(attr_values, expected_values);
Ok(())
}
#[test]
fn duplicates_cause_errors() {
// given
let tokens = quote! {SomeCommand(duplicate=1, something=2, duplicate=3)};
// when
let err = extract_name_values(tokens).expect_err("should have failed");
// then
let messages = err.into_iter().map(|e| e.to_string()).collect::<Vec<_>>();
assert_eq!(messages, vec!["original defined here:", "duplicate!"]);
}
#[test]
fn attr_names_cannot_be_paths() {
let tokens = quote! {SomeCommand(something::duplicate=1)};
let err = extract_name_values(tokens).expect_err("should have failed");
assert_eq!(
err.to_string(),
"attribute name cannot be a `Path` -- i.e. must not contain ':'"
);
}
#[test]
fn only_name_value_is_accepted() {
let tokens = quote! {SomeCommand(name="value", "something_else")};
let err = extract_name_values(tokens).expect_err("should have failed");
assert_eq!(err.to_string(), "expected name='value'");
}
#[test]
fn validates_correct_names() -> syn::Result<()> {
let tokens = quote! {SomeCommand(name="value", other="something_else")};
let name_values = extract_name_values(tokens)?;
let result = name_values.validate_has_no_other_names(&["name", "other", "another"]);
assert!(result.is_ok());
Ok(())
}
#[test]
fn catches_incorrect_names() -> syn::Result<()> {
let name_values =
extract_name_values(quote! {SomeCommand(name="value", other="something_else")})?;
let err = name_values
.validate_has_no_other_names(&["name", "other_is_not_allowed"])
.expect_err("should have failed");
assert_eq!(
err.to_string(),
"attribute 'other' not recognized. Expected one of: 'name', 'other_is_not_allowed'"
);
Ok(())
}
#[test]
fn can_get_lit_strs() -> syn::Result<()> {
let name_values = extract_name_values(quote! {SomeCommand(name="value")})?;
let lit_str = name_values.get_as_lit_str("name")?;
assert_eq!(lit_str.value(), "value");
Ok(())
}
#[test]
fn cannot_get_lit_str_if_type_is_wrong() -> syn::Result<()> {
let name_values = extract_name_values(quote! {SomeCommand(name=true)})?;
let err = name_values
.get_as_lit_str("name")
.expect_err("should have failed");
assert_eq!(
err.to_string(),
"expected the attribute 'name' to have a string value"
);
Ok(())
}
#[test]
fn lit_str_getter_complains_value_is_missing() -> syn::Result<()> {
let name_values = extract_name_values(quote! {SomeCommand(name=true)})?;
let err = name_values
.get_as_lit_str("missing")
.expect_err("should have failed");
assert_eq!(err.to_string(), "missing attribute 'missing'");
Ok(())
}
fn extract_name_values(stream: TokenStream) -> syn::Result<UniqueNameValues> {
let command = Command::parse_single_from_token_stream(stream)?;
UniqueNameValues::new(command.contents)
}
}
| rust | Apache-2.0 | 865e00c295de8b4a0a1ef7ac926c3c8266d5151b | 2026-01-04T15:31:59.450823Z | false |
FuelLabs/fuels-rs | https://github.com/FuelLabs/fuels-rs/blob/865e00c295de8b4a0a1ef7ac926c3c8266d5151b/packages/fuels-macros/src/abigen/parsing.rs | packages/fuels-macros/src/abigen/parsing.rs | use fuels_code_gen::{Abi, AbigenTarget, ProgramType};
use syn::{
LitStr, Result,
parse::{Parse, ParseStream},
};
use crate::parse_utils::{Command, UniqueNameValues};
impl From<MacroAbigenTargets> for Vec<AbigenTarget> {
fn from(targets: MacroAbigenTargets) -> Self {
targets.targets.into_iter().map(Into::into).collect()
}
}
impl From<MacroAbigenTarget> for AbigenTarget {
fn from(macro_target: MacroAbigenTarget) -> Self {
AbigenTarget::new(
macro_target.name,
macro_target.source,
macro_target.program_type,
)
}
}
// Although identical to `AbigenTarget` from fuels-core, due to the orphan rule
// we cannot implement Parse for the latter.
#[derive(Debug)]
pub(crate) struct MacroAbigenTarget {
pub(crate) name: String,
pub(crate) source: Abi,
pub program_type: ProgramType,
}
pub(crate) struct MacroAbigenTargets {
targets: Vec<MacroAbigenTarget>,
}
impl Parse for MacroAbigenTargets {
fn parse(input: ParseStream) -> Result<Self> {
let targets = Command::parse_multiple(input)?
.into_iter()
.map(MacroAbigenTarget::new)
.collect::<Result<_>>()?;
Ok(Self { targets })
}
}
impl MacroAbigenTarget {
pub fn new(command: Command) -> Result<Self> {
let program_type = command.name.try_into()?;
let name_values = UniqueNameValues::new(command.contents)?;
name_values.validate_has_no_other_names(&["name", "abi"])?;
let name = name_values.get_as_lit_str("name")?.value();
let abi_lit_str = name_values.get_as_lit_str("abi")?;
let source = Self::parse_inline_or_load_abi(abi_lit_str)?;
Ok(Self {
name,
source,
program_type,
})
}
fn parse_inline_or_load_abi(abi_lit_str: &LitStr) -> Result<Abi> {
let abi_string = abi_lit_str.value();
let abi_str = abi_string.trim();
if abi_str.starts_with('{') || abi_str.starts_with('[') || abi_str.starts_with('\n') {
abi_str.parse()
} else {
Abi::load_from(abi_str)
}
.map_err(|e| syn::Error::new(abi_lit_str.span(), e.to_string()))
}
}
| rust | Apache-2.0 | 865e00c295de8b4a0a1ef7ac926c3c8266d5151b | 2026-01-04T15:31:59.450823Z | false |
FuelLabs/fuels-rs | https://github.com/FuelLabs/fuels-rs/blob/865e00c295de8b4a0a1ef7ac926c3c8266d5151b/packages/fuels-macros/src/derive/tokenizable.rs | packages/fuels-macros/src/derive/tokenizable.rs | use itertools::Itertools;
use proc_macro2::{Ident, TokenStream};
use quote::quote;
use syn::{Data, DataEnum, DataStruct, DeriveInput, Error, Generics, Result};
use crate::{
derive::{
utils,
utils::{find_attr, get_path_from_attr_or, std_lib_path},
},
parse_utils::{Members, validate_and_extract_generic_types},
};
pub fn generate_tokenizable_impl(input: DeriveInput) -> Result<TokenStream> {
let fuels_types_path =
get_path_from_attr_or("FuelsTypesPath", &input.attrs, quote! {::fuels::types})?;
let fuels_core_path =
get_path_from_attr_or("FuelsCorePath", &input.attrs, quote! {::fuels::core})?;
let no_std = find_attr("NoStd", &input.attrs).is_some();
match input.data {
Data::Struct(struct_contents) => tokenizable_for_struct(
input.ident,
input.generics,
struct_contents,
fuels_types_path,
fuels_core_path,
no_std,
),
Data::Enum(enum_contents) => tokenizable_for_enum(
input.ident,
input.generics,
enum_contents,
fuels_types_path,
fuels_core_path,
no_std,
),
_ => Err(Error::new_spanned(input, "Union type is not supported")),
}
}
fn tokenizable_for_struct(
name: Ident,
generics: Generics,
contents: DataStruct,
fuels_types_path: TokenStream,
fuels_core_path: TokenStream,
no_std: bool,
) -> Result<TokenStream> {
validate_and_extract_generic_types(&generics)?;
let (impl_gen, type_gen, where_clause) = generics.split_for_impl();
let struct_name_str = name.to_string();
let members = Members::from_struct(contents, fuels_core_path.clone())?;
let field_names = members.names().collect::<Vec<_>>();
let ignored_field_names = members.ignored_names().collect_vec();
let std_lib = std_lib_path(no_std);
Ok(quote! {
impl #impl_gen #fuels_core_path::traits::Tokenizable for #name #type_gen #where_clause {
fn into_token(self) -> #fuels_types_path::Token {
let tokens = #std_lib::vec![#(#fuels_core_path::traits::Tokenizable::into_token(self.#field_names)),*];
#fuels_types_path::Token::Struct(tokens)
}
fn from_token(token: #fuels_types_path::Token) -> #fuels_types_path::errors::Result<Self> {
match token {
#fuels_types_path::Token::Struct(tokens) => {
let mut tokens_iter = tokens.into_iter();
let mut next_token = move || { tokens_iter
.next()
.ok_or_else(|| {
#fuels_types_path::errors::Error::Codec(
#std_lib::format!(
"ran out of tokens before `{}` has finished construction",
#struct_name_str
)
)
}
)
};
::core::result::Result::Ok(Self {
#(
#field_names: #fuels_core_path::traits::Tokenizable::from_token(next_token()?)?,
)*
#(#ignored_field_names: ::core::default::Default::default(),)*
})
},
other => ::core::result::Result::Err(
#fuels_types_path::errors::Error::Codec(
#std_lib::format!(
"error while constructing `{}`. Expected token of type `Token::Struct`, \
got `{:?}`",
#struct_name_str,
other
)
)
),
}
}
}
})
}
fn tokenizable_for_enum(
name: Ident,
generics: Generics,
contents: DataEnum,
fuels_types_path: TokenStream,
fuels_core_path: TokenStream,
no_std: bool,
) -> Result<TokenStream> {
validate_and_extract_generic_types(&generics)?;
let (impl_gen, type_gen, where_clause) = generics.split_for_impl();
let name_stringified = name.to_string();
let variants = utils::extract_variants(contents.variants, fuels_core_path.clone())?;
let discriminant_and_token = variants.variant_into_discriminant_and_token();
let constructed_variant = variants.variant_from_discriminant_and_token(no_std);
let std_lib = std_lib_path(no_std);
Ok(quote! {
impl #impl_gen #fuels_core_path::traits::Tokenizable for #name #type_gen #where_clause {
fn into_token(self) -> #fuels_types_path::Token {
let (discriminant, token) = #discriminant_and_token;
let enum_variants = match <Self as #fuels_core_path::traits::Parameterize>::param_type() {
#fuels_types_path::param_types::ParamType::Enum{enum_variants, ..} => enum_variants,
other => ::std::panic!(
"calling {}::param_type() must return a `ParamType::Enum` but instead it returned: `{:?}`",
#name_stringified,
other
)
};
#fuels_types_path::Token::Enum(#std_lib::boxed::Box::new((discriminant, token, enum_variants)))
}
fn from_token(token: #fuels_types_path::Token) -> #fuels_types_path::errors::Result<Self>
where
Self: Sized,
{
match token {
#fuels_types_path::Token::Enum(selector) => {
let (discriminant, variant_token, _) = *selector;
#constructed_variant
}
_ => ::core::result::Result::Err(
#std_lib::format!("token `{}` is not of the type `Token::Enum`", token)
),
}.map_err(|e| {
#fuels_types_path::errors::Error::Codec(
#std_lib::format!(
"error while instantiating `{}` from token `{}`",
#name_stringified,
e
)
)
})
}
}
})
}
| rust | Apache-2.0 | 865e00c295de8b4a0a1ef7ac926c3c8266d5151b | 2026-01-04T15:31:59.450823Z | false |
FuelLabs/fuels-rs | https://github.com/FuelLabs/fuels-rs/blob/865e00c295de8b4a0a1ef7ac926c3c8266d5151b/packages/fuels-macros/src/derive/utils.rs | packages/fuels-macros/src/derive/utils.rs | use fuels_code_gen::utils::TypePath;
use proc_macro2::{Ident, TokenStream};
use quote::{ToTokens, quote};
use syn::{Attribute, Error, Expr, ExprLit, Fields, Lit, Meta, Result, Variant};
use crate::parse_utils::has_ignore_attr;
pub(crate) fn get_path_from_attr_or(
attr_name: &str,
attrs: &[Attribute],
default: TokenStream,
) -> Result<TokenStream> {
let Some(attr) = find_attr(attr_name, attrs) else {
return Ok(default);
};
let Meta::NameValue(name_value) = &attr.meta else {
return Err(Error::new_spanned(
attr.meta.path(),
"expected name='value'",
));
};
let Expr::Lit(ExprLit {
lit: Lit::Str(lit_str),
..
}) = &name_value.value
else {
return Err(Error::new_spanned(
&name_value.value,
"expected string literal",
));
};
TypePath::new(lit_str.value())
.map_err(|_| Error::new_spanned(lit_str.value(), "invalid path"))
.map(|type_path| type_path.to_token_stream())
}
pub(crate) fn find_attr<'a>(name: &str, attrs: &'a [Attribute]) -> Option<&'a Attribute> {
attrs.iter().find(|attr| {
attr.path()
.get_ident()
.map(|ident| ident == name)
.unwrap_or(false)
})
}
pub(crate) struct VariantInfo {
name: Ident,
is_unit: bool,
}
pub(crate) enum ExtractedVariant {
Normal {
info: VariantInfo,
discriminant: u64,
},
Ignored {
info: VariantInfo,
},
}
pub(crate) fn extract_variants(
contents: impl IntoIterator<Item = Variant>,
fuels_core_path: TokenStream,
) -> Result<ExtractedVariants> {
let variants = contents
.into_iter()
.enumerate()
.map(|(discriminant, variant)| -> Result<_> {
let is_unit = matches!(variant.fields, Fields::Unit);
if has_ignore_attr(&variant.attrs) {
Ok(ExtractedVariant::Ignored {
info: VariantInfo {
name: variant.ident,
is_unit,
},
})
} else {
validate_variant_type(&variant)?;
let discriminant = discriminant.try_into().map_err(|_| {
Error::new_spanned(&variant.ident, "enums cannot have more than 256 variants")
})?;
Ok(ExtractedVariant::Normal {
info: VariantInfo {
name: variant.ident,
is_unit,
},
discriminant,
})
}
})
.collect::<Result<_>>()?;
Ok(ExtractedVariants {
variants,
fuels_core_path,
})
}
pub(crate) struct ExtractedVariants {
fuels_core_path: TokenStream,
variants: Vec<ExtractedVariant>,
}
impl ExtractedVariants {
pub(crate) fn variant_into_discriminant_and_token(&self) -> TokenStream {
let match_branches = self.variants.iter().map(|variant|
match variant {
ExtractedVariant::Normal { info: VariantInfo{ name, is_unit }, discriminant } => {
let fuels_core_path = &self.fuels_core_path;
if *is_unit {
quote! { Self::#name => (#discriminant, #fuels_core_path::traits::Tokenizable::into_token(())) }
} else {
quote! { Self::#name(inner) => (#discriminant, #fuels_core_path::traits::Tokenizable::into_token(inner))}
}
},
ExtractedVariant::Ignored { info: VariantInfo{ name, is_unit } } => {
let panic_expression = {
let name_stringified = name.to_string();
quote! {::core::panic!("variant `{}` should never be constructed", #name_stringified)}
};
if *is_unit {
quote! { Self::#name => #panic_expression }
} else {
quote! { Self::#name(..) => #panic_expression }
}
}
}
);
quote! {
match self {
#(#match_branches),*
}
}
}
pub(crate) fn variant_from_discriminant_and_token(&self, no_std: bool) -> TokenStream {
let match_discriminant = self
.variants
.iter()
.filter_map(|variant| match variant {
ExtractedVariant::Normal { info, discriminant } => Some((info, discriminant)),
_ => None,
})
.map(|(VariantInfo { name, is_unit }, discriminant)| {
let fuels_core_path = &self.fuels_core_path;
let variant_value = if *is_unit {
quote! {}
} else {
quote! { (#fuels_core_path::traits::Tokenizable::from_token(variant_token)?) }
};
quote! { #discriminant => ::core::result::Result::Ok(Self::#name #variant_value)}
});
let std_lib = std_lib_path(no_std);
quote! {
match discriminant {
#(#match_discriminant,)*
_ => ::core::result::Result::Err(#std_lib::format!(
"discriminant {} doesn't point to any of the enums variants", discriminant
)),
}
}
}
}
fn validate_variant_type(variant: &Variant) -> Result<()> {
match &variant.fields {
Fields::Named(named_fields) => {
return Err(Error::new_spanned(
named_fields.clone(),
"struct like enum variants are not supported".to_string(),
));
}
Fields::Unnamed(unnamed_fields) => {
let fields = &unnamed_fields.unnamed;
if fields.len() != 1 {
return Err(Error::new_spanned(
unnamed_fields.clone(),
"tuple-like enum variants must contain exactly one element".to_string(),
));
}
}
_ => {}
}
Ok(())
}
pub(crate) fn std_lib_path(no_std: bool) -> TokenStream {
if no_std {
quote! {::alloc}
} else {
quote! {::std}
}
}
| rust | Apache-2.0 | 865e00c295de8b4a0a1ef7ac926c3c8266d5151b | 2026-01-04T15:31:59.450823Z | false |
FuelLabs/fuels-rs | https://github.com/FuelLabs/fuels-rs/blob/865e00c295de8b4a0a1ef7ac926c3c8266d5151b/packages/fuels-macros/src/derive/parameterize.rs | packages/fuels-macros/src/derive/parameterize.rs | use proc_macro2::{Ident, TokenStream};
use quote::quote;
use syn::{Data, DataEnum, DataStruct, DeriveInput, Error, Generics, Result};
use crate::{
derive::utils::{find_attr, get_path_from_attr_or, std_lib_path},
parse_utils::{Members, validate_and_extract_generic_types},
};
pub fn generate_parameterize_impl(input: DeriveInput) -> Result<TokenStream> {
let fuels_types_path =
get_path_from_attr_or("FuelsTypesPath", &input.attrs, quote! {::fuels::types})?;
let fuels_core_path =
get_path_from_attr_or("FuelsCorePath", &input.attrs, quote! {::fuels::core})?;
let no_std = find_attr("NoStd", &input.attrs).is_some();
match input.data {
Data::Struct(struct_contents) => parameterize_for_struct(
input.ident,
input.generics,
struct_contents,
fuels_types_path,
fuels_core_path,
no_std,
),
Data::Enum(enum_contents) => parameterize_for_enum(
input.ident,
input.generics,
enum_contents,
fuels_types_path,
fuels_core_path,
no_std,
),
_ => Err(Error::new_spanned(input, "union type is not supported")),
}
}
fn parameterize_for_struct(
name: Ident,
generics: Generics,
contents: DataStruct,
fuels_types_path: TokenStream,
fuels_core_path: TokenStream,
no_std: bool,
) -> Result<TokenStream> {
let (impl_gen, type_gen, where_clause) = generics.split_for_impl();
let name_stringified = name.to_string();
let members = Members::from_struct(contents, fuels_core_path.clone())?;
let field_names = members.names_as_strings();
let param_type_calls = members.param_type_calls();
let generic_param_types = parameterize_generic_params(&generics, &fuels_core_path)?;
let std_lib = std_lib_path(no_std);
Ok(quote! {
impl #impl_gen #fuels_core_path::traits::Parameterize for #name #type_gen #where_clause {
fn param_type() -> #fuels_types_path::param_types::ParamType {
#fuels_types_path::param_types::ParamType::Struct{
name: #std_lib::string::String::from(#name_stringified),
fields: #std_lib::vec![#((#field_names, #param_type_calls)),*],
generics: #std_lib::vec![#(#generic_param_types),*],
}
}
}
})
}
fn parameterize_generic_params(
generics: &Generics,
fuels_core_path: &TokenStream,
) -> Result<Vec<TokenStream>> {
let parameterize_calls = validate_and_extract_generic_types(generics)?
.into_iter()
.map(|type_param| {
let ident = &type_param.ident;
quote! {<#ident as #fuels_core_path::traits::Parameterize>::param_type()}
})
.collect();
Ok(parameterize_calls)
}
fn parameterize_for_enum(
name: Ident,
generics: Generics,
contents: DataEnum,
fuels_types_path: TokenStream,
fuels_core_path: TokenStream,
no_std: bool,
) -> Result<TokenStream> {
let (impl_gen, type_gen, where_clause) = generics.split_for_impl();
let enum_name_str = name.to_string();
let members = Members::from_enum(contents, fuels_core_path.clone())?;
let variant_names = members.names_as_strings();
let variant_param_types = members.param_type_calls();
let generic_param_types = parameterize_generic_params(&generics, &fuels_core_path)?;
let std_lib = std_lib_path(no_std);
Ok(quote! {
impl #impl_gen #fuels_core_path::traits::Parameterize for #name #type_gen #where_clause {
fn param_type() -> #fuels_types_path::param_types::ParamType {
let variants = #std_lib::vec![#((#variant_names, #variant_param_types)),*];
let enum_variants = #fuels_types_path::param_types::EnumVariants::new(variants)
.unwrap_or_else(|_| ::std::panic!(
"{} has no variants which isn't allowed",
#enum_name_str
)
);
#fuels_types_path::param_types::ParamType::Enum {
name: #std_lib::string::String::from(#enum_name_str),
enum_variants,
generics: #std_lib::vec![#(#generic_param_types),*]
}
}
}
})
}
| rust | Apache-2.0 | 865e00c295de8b4a0a1ef7ac926c3c8266d5151b | 2026-01-04T15:31:59.450823Z | false |
FuelLabs/fuels-rs | https://github.com/FuelLabs/fuels-rs/blob/865e00c295de8b4a0a1ef7ac926c3c8266d5151b/packages/fuels-macros/src/derive/try_from.rs | packages/fuels-macros/src/derive/try_from.rs | use proc_macro2::TokenStream;
use quote::quote;
use syn::{Data, DeriveInput, Error, Result};
use crate::derive::utils::{find_attr, get_path_from_attr_or, std_lib_path};
pub fn generate_try_from_impl(input: DeriveInput) -> Result<TokenStream> {
let fuels_types_path =
get_path_from_attr_or("FuelsTypesPath", &input.attrs, quote! {::fuels::types})?;
let fuels_core_path =
get_path_from_attr_or("FuelsCorePath", &input.attrs, quote! {::fuels::core})?;
let no_std = find_attr("NoStd", &input.attrs).is_some();
match input.data {
Data::Enum(_) | Data::Struct(_) => {
impl_try_from(input, fuels_types_path, fuels_core_path, no_std)
}
Data::Union(union) => Err(Error::new_spanned(
union.union_token,
"unions are not supported",
)),
}
}
fn impl_try_from(
input: DeriveInput,
fuels_types_path: TokenStream,
fuels_core_path: TokenStream,
no_std: bool,
) -> Result<TokenStream> {
let name = &input.ident;
let (impl_gen, type_gen, where_clause) = input.generics.split_for_impl();
let std_lib = std_lib_path(no_std);
Ok(quote! {
impl #impl_gen TryFrom<&[u8]> for #name #type_gen #where_clause {
type Error = #fuels_types_path::errors::Error;
fn try_from(bytes: &[u8]) -> #fuels_types_path::errors::Result<Self> {
#fuels_core_path::codec::try_from_bytes(bytes, ::std::default::Default::default())
}
}
impl #impl_gen TryFrom<&#std_lib::vec::Vec<u8>> for #name #type_gen #where_clause {
type Error = #fuels_types_path::errors::Error;
fn try_from(bytes: &#std_lib::vec::Vec<u8>) -> #fuels_types_path::errors::Result<Self> {
::core::convert::TryInto::try_into(bytes.as_slice())
}
}
impl #impl_gen TryFrom<#std_lib::vec::Vec<u8>> for #name #type_gen #where_clause {
type Error = #fuels_types_path::errors::Error;
fn try_from(bytes: #std_lib::vec::Vec<u8>) -> #fuels_types_path::errors::Result<Self> {
::core::convert::TryInto::try_into(bytes.as_slice())
}
}
})
}
| rust | Apache-2.0 | 865e00c295de8b4a0a1ef7ac926c3c8266d5151b | 2026-01-04T15:31:59.450823Z | false |
FuelLabs/fuels-rs | https://github.com/FuelLabs/fuels-rs/blob/865e00c295de8b4a0a1ef7ac926c3c8266d5151b/packages/fuels-macros/tests/macro_usage.rs | packages/fuels-macros/tests/macro_usage.rs | #[cfg(test)]
mod tests {
#[test]
fn ui() {
let t = trybuild::TestCases::new();
t.compile_fail("tests/ui/abigen/*.rs");
t.compile_fail("tests/ui/setup_program_test/*.rs");
t.compile_fail("tests/ui/derive/*/*.rs");
}
}
| rust | Apache-2.0 | 865e00c295de8b4a0a1ef7ac926c3c8266d5151b | 2026-01-04T15:31:59.450823Z | false |
FuelLabs/fuels-rs | https://github.com/FuelLabs/fuels-rs/blob/865e00c295de8b4a0a1ef7ac926c3c8266d5151b/packages/fuels-macros/tests/ui/setup_program_test/invalid_project_path.rs | packages/fuels-macros/tests/ui/setup_program_test/invalid_project_path.rs | use fuels_macros::setup_program_test;
setup_program_test!(Abigen(Contract(name = "MyContract", project = ".")));
fn main() {}
| rust | Apache-2.0 | 865e00c295de8b4a0a1ef7ac926c3c8266d5151b | 2026-01-04T15:31:59.450823Z | false |
FuelLabs/fuels-rs | https://github.com/FuelLabs/fuels-rs/blob/865e00c295de8b4a0a1ef7ac926c3c8266d5151b/packages/fuels-macros/tests/ui/setup_program_test/unknown_options_key.rs | packages/fuels-macros/tests/ui/setup_program_test/unknown_options_key.rs | use fuels_macros::setup_program_test;
setup_program_test!(Options(unknown = "debug"));
fn main() {}
| rust | Apache-2.0 | 865e00c295de8b4a0a1ef7ac926c3c8266d5151b | 2026-01-04T15:31:59.450823Z | false |
FuelLabs/fuels-rs | https://github.com/FuelLabs/fuels-rs/blob/865e00c295de8b4a0a1ef7ac926c3c8266d5151b/packages/fuels-macros/tests/ui/setup_program_test/unknown_command.rs | packages/fuels-macros/tests/ui/setup_program_test/unknown_command.rs | use fuels_macros::setup_program_test;
setup_program_test!(
Abigen(Contract(project = "some_project", name = "SomeContract")),
Deploy(
name = "some_instance",
contract = "SomeContract",
wallet = "some_wallet"
),
UnknownCommand()
);
fn main() {}
| rust | Apache-2.0 | 865e00c295de8b4a0a1ef7ac926c3c8266d5151b | 2026-01-04T15:31:59.450823Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.