Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

sudt's amount type should be u128 #106

Merged
merged 3 commits into from
Mar 6, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 19 additions & 6 deletions src/transaction/builder/sudt.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ use crate::{
tx_builder::{BalanceTxCapacityError, TxBuilderError},
NetworkInfo, NetworkType, TransactionWithScriptGroups,
};
use anyhow::anyhow;

use ckb_types::{
core::{Capacity, ScriptHashType},
Expand Down Expand Up @@ -67,7 +68,7 @@ impl SudtTransactionBuilder {
}

/// Add an output cell with the given lock script and sudt amount
pub fn add_output<S: Into<Script>>(&mut self, output_lock_script: S, sudt_amount: u64) {
pub fn add_output<S: Into<Script>>(&mut self, output_lock_script: S, sudt_amount: u128) {
let type_script = build_sudt_type_script(
self.configuration.network_info(),
&self.sudt_owner_lock_script,
Expand All @@ -89,6 +90,18 @@ impl SudtTransactionBuilder {
}
}

fn parse_u128(data: &[u8]) -> Result<u128, TxBuilderError> {
if data.len() > std::mem::size_of::<u128>() {
return Err(TxBuilderError::Other(anyhow!(
"stdt_amount bytes length greater than 128"
)));
}

let mut data_bytes: Vec<u8> = data.into();
data_bytes.extend(std::iter::repeat(0_u8).take(std::mem::size_of::<u128>() - data.len()));
Ok(u128::from_le_bytes(data_bytes.try_into().unwrap()))
}

impl CkbTransactionBuilder for SudtTransactionBuilder {
fn build(
mut self,
Expand Down Expand Up @@ -122,18 +135,18 @@ impl CkbTransactionBuilder for SudtTransactionBuilder {
let mut sudt_input_iter = input_iter.clone();
sudt_input_iter.set_type_script(Some(sudt_type_script));

let outputs_sudt_amount: u64 = tx
let outputs_sudt_amount: u128 = tx
.outputs_data
.iter()
.map(|data| u64::from_le_bytes(data.raw_data().as_ref().try_into().unwrap()))
.sum();
.map(|data| parse_u128(data.as_slice()))
.collect::<Result<Vec<u128>, TxBuilderError>>()
.map(|u128_vec| u128_vec.iter().sum())?;

let mut inputs_sudt_amount = 0;

for input in sudt_input_iter {
let input = input?;
let input_amount =
u64::from_le_bytes(input.live_cell.output_data.as_ref().try_into().unwrap());
let input_amount = parse_u128(input.live_cell.output_data.as_ref())?;
inputs_sudt_amount += input_amount;
input_iter.push_input(input);
if inputs_sudt_amount >= outputs_sudt_amount {
Expand Down
Loading