diff --git a/.github/workflows/rustdoc.yml b/.github/workflows/rustdoc.yml index d991a94..62ad4ee 100644 --- a/.github/workflows/rustdoc.yml +++ b/.github/workflows/rustdoc.yml @@ -2,7 +2,7 @@ name: rustdoc on: push: - branches: [ master ] + branches: [master] workflow_dispatch: env: diff --git a/Makefile b/Makefile index 9d1d5cc..778d3e4 100644 --- a/Makefile +++ b/Makefile @@ -4,7 +4,7 @@ all:: ci .PHONY: check-features check-features: - $(MAKE) -C crates/sui-sdk check-features + $(MAKE) -C crates/iota-rust-sdk check-features .PHONY: check-fmt check-fmt: @@ -21,7 +21,7 @@ test: .PHONY: wasm wasm: - $(MAKE) -C crates/sui-sdk wasm + $(MAKE) -C crates/iota-rust-sdk wasm .PHONY: doc doc: diff --git a/README.md b/README.md index 90cde13..0aa4d29 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,5 @@ -# Sui Sdk +# IOTA Sdk -[![Documentation (master)](https://img.shields.io/badge/docs-master-59f)](https://mystenlabs.github.io/sui-rust-sdk/sui_sdk/) +[![Documentation (master)](https://img.shields.io/badge/docs-master-59f)](https://github.com/iotaledger/iota-rust-sdk/iota_sdk/) -A WIP from-scratch rust sdk for the sui blockchain +A WIP from-scratch rust sdk for the IOTA blockchain diff --git a/crates/sui-sdk/Cargo.toml b/crates/iota-rust-sdk/Cargo.toml similarity index 81% rename from crates/sui-sdk/Cargo.toml rename to crates/iota-rust-sdk/Cargo.toml index e19cbbd..5aff347 100644 --- a/crates/sui-sdk/Cargo.toml +++ b/crates/iota-rust-sdk/Cargo.toml @@ -1,47 +1,55 @@ [package] -name = "sui-sdk" +name = "iota-rust-sdk" version = "0.0.0" -authors = ["Brandon Williams "] -license = "Apache-2.0" +authors = ["IOTA Foundation "] edition = "2021" +license = "Apache-2.0" publish = false readme = "README.md" -description = "Sdk for the Sui Blockchain" +description = "Sdk for the IOTA Blockchain" [package.metadata.docs.rs] # To build locally: # RUSTDOCFLAGS="--cfg=doc_cfg -Zunstable-options --generate-link-to-definition" RUSTC_BOOTSTRAP=1 cargo doc --all-features --no-deps --open all-features = true rustdoc-args = [ - # Enable doc_cfg showing the required features. - "--cfg=doc_cfg", + # Enable doc_cfg showing the required features. + "--cfg=doc_cfg", - # Generate links to definition in rustdoc source code pages - # https://github.com/rust-lang/rust/pull/84176 - "-Zunstable-options", "--generate-link-to-definition" + # Generate links to definition in rustdoc source code pages + # https://github.com/rust-lang/rust/pull/84176 + "-Zunstable-options", + "--generate-link-to-definition", ] [features] default = [] -serde = ["dep:serde", "dep:serde_derive", "dep:serde_with", "dep:bcs", "dep:serde_json", "roaring/std"] +serde = [ + "dep:serde", + "dep:serde_derive", + "dep:serde_with", + "dep:bcs", + "dep:serde_json", + "roaring/std", +] schemars = ["serde", "dep:schemars", "dep:serde_json"] rand = ["dep:rand_core"] hash = ["dep:blake2"] [dependencies] base64ct = { version = "1.6.0", features = ["alloc"] } +bnum = "0.11.0" bs58 = "0.5.1" hex = "0.4.3" roaring = { version = "0.10.6", default-features = false } -bnum = "0.11.0" winnow = "0.6.18" # Serialization and Deserialization support +bcs = { version = "0.1.6", optional = true } serde = { version = "1.0.190", optional = true } serde_derive = { version = "1.0.190", optional = true } -serde_with = { version = "3.9", default-features = false, features = ["alloc"], optional = true } -bcs = { version = "0.1.6", optional = true } serde_json = { version = "1.0.114", optional = true } +serde_with = { version = "3.9", default-features = false, features = ["alloc"], optional = true } # JsonSchema definitions for types, useful for generating an OpenAPI Specificaiton. schemars = { version = "0.8.21", optional = true } @@ -54,10 +62,10 @@ blake2 = { version = "0.10.6", optional = true } [dev-dependencies] bcs = "0.1.6" -serde_json = "1.0.114" -num-bigint = "0.4.4" jsonschema = { version = "0.18", default-features = false } +num-bigint = "0.4.4" paste = "1.0.15" +serde_json = "1.0.114" # proptest support in tests # diff --git a/crates/sui-sdk/Makefile b/crates/iota-rust-sdk/Makefile similarity index 100% rename from crates/sui-sdk/Makefile rename to crates/iota-rust-sdk/Makefile diff --git a/crates/sui-sdk/src/hash.rs b/crates/iota-rust-sdk/src/hash.rs similarity index 97% rename from crates/sui-sdk/src/hash.rs rename to crates/iota-rust-sdk/src/hash.rs index 2a298e7..1630026 100644 --- a/crates/sui-sdk/src/hash.rs +++ b/crates/iota-rust-sdk/src/hash.rs @@ -1,8 +1,7 @@ -use crate::types::Address; -use crate::types::Digest; - use blake2::Digest as DigestTrait; +use crate::types::{Address, Digest}; + type Blake2b256 = blake2::Blake2b; #[derive(Debug, Default)] @@ -226,9 +225,9 @@ mod type_digest { } } -/// A 1-byte domain separator for hashing Object ID in Sui. It is starting from 0xf0 -/// to ensure no hashing collision for any ObjectId vs Address which is derived -/// as the hash of `flag || pubkey`. +/// A 1-byte domain separator for hashing Object ID in Iota. It is starting from +/// 0xf0 to ensure no hashing collision for any ObjectId vs Address which is +/// derived as the hash of `flag || pubkey`. #[derive(Copy, Clone, PartialEq, Eq, Debug, Hash)] #[cfg_attr(test, derive(test_strategy::Arbitrary))] #[repr(u8)] @@ -241,7 +240,8 @@ enum HashingIntent { impl crate::types::ObjectId { /// Create an ObjectId from `TransactionDigest` and `count`. /// - /// `count` is the number of objects that have been created during a transactions. + /// `count` is the number of objects that have been created during a + /// transactions. pub fn derive_id(digest: crate::types::TransactionDigest, count: u64) -> Self { let mut hasher = Hasher::new(); hasher.update([HashingIntent::RegularObjectId as u8]); @@ -280,13 +280,13 @@ impl crate::types::ObjectId { #[cfg(test)] mod test { - use super::HashingIntent; - use crate::types::SignatureScheme; use test_strategy::proptest; - #[cfg(target_arch = "wasm32")] use wasm_bindgen_test::wasm_bindgen_test as test; + use super::HashingIntent; + use crate::types::SignatureScheme; + impl HashingIntent { fn from_byte(byte: u8) -> Result { match byte { diff --git a/crates/sui-sdk/src/lib.rs b/crates/iota-rust-sdk/src/lib.rs similarity index 94% rename from crates/sui-sdk/src/lib.rs rename to crates/iota-rust-sdk/src/lib.rs index c89d871..30bf517 100644 --- a/crates/sui-sdk/src/lib.rs +++ b/crates/iota-rust-sdk/src/lib.rs @@ -8,17 +8,12 @@ pub mod hash; #[cfg(feature = "serde")] mod _serde { - use base64ct::Base64; - use base64ct::Encoding; - use serde::Deserialize; - use serde::Deserializer; - use serde::Serialize; - use serde::Serializer; - use serde_with::Bytes; - use serde_with::DeserializeAs; - use serde_with::SerializeAs; use std::borrow::Cow; + use base64ct::{Base64, Encoding}; + use serde::{Deserialize, Deserializer, Serialize, Serializer}; + use serde_with::{Bytes, DeserializeAs, SerializeAs}; + pub(crate) type ReadableDisplay = ::serde_with::As<::serde_with::IfIsHumanReadable<::serde_with::DisplayFromStr>>; @@ -124,10 +119,10 @@ mod _serde { #[cfg(feature = "schemars")] mod _schemars { - use schemars::schema::InstanceType; - use schemars::schema::Metadata; - use schemars::schema::SchemaObject; - use schemars::JsonSchema; + use schemars::{ + schema::{InstanceType, Metadata, SchemaObject}, + JsonSchema, + }; pub(crate) struct U64; diff --git a/crates/sui-sdk/src/types/address.rs b/crates/iota-rust-sdk/src/types/address.rs similarity index 95% rename from crates/sui-sdk/src/types/address.rs rename to crates/iota-rust-sdk/src/types/address.rs index 21e4289..1a039d2 100644 --- a/crates/sui-sdk/src/types/address.rs +++ b/crates/iota-rust-sdk/src/types/address.rs @@ -73,7 +73,7 @@ impl Address { <[u8; Self::LENGTH] as hex::FromHex>::from_hex(hex) } .map(Self) - //TODO fix error to contain hex parse error + // TODO fix error to contain hex parse error .map_err(|_| AddressParseError) } @@ -201,16 +201,13 @@ impl schemars::JsonSchema for Address { } fn json_schema(_: &mut schemars::gen::SchemaGenerator) -> schemars::schema::Schema { - use schemars::schema::InstanceType; - use schemars::schema::Metadata; - use schemars::schema::SchemaObject; - use schemars::schema::StringValidation; + use schemars::schema::{InstanceType, Metadata, SchemaObject, StringValidation}; let hex_length = Address::LENGTH * 2; SchemaObject { metadata: Some(Box::new(Metadata { title: Some(Self::schema_name()), - description: Some("A 32-byte Sui address, encoded as a hex string.".to_owned()), + description: Some("A 32-byte Iota address, encoded as a hex string.".to_owned()), examples: vec![serde_json::to_value(Address::TWO).unwrap()], ..Default::default() })), @@ -229,12 +226,12 @@ impl schemars::JsonSchema for Address { #[cfg(test)] mod test { - use super::*; use test_strategy::proptest; - #[cfg(target_arch = "wasm32")] use wasm_bindgen_test::wasm_bindgen_test as test; + use super::*; + #[test] fn hex_parsing() { let actual = Address::from_hex("0x2").unwrap(); diff --git a/crates/sui-sdk/src/types/checkpoint.rs b/crates/iota-rust-sdk/src/types/checkpoint.rs similarity index 92% rename from crates/sui-sdk/src/types/checkpoint.rs rename to crates/iota-rust-sdk/src/types/checkpoint.rs index 42158a4..2498ede 100644 --- a/crates/sui-sdk/src/types/checkpoint.rs +++ b/crates/iota-rust-sdk/src/types/checkpoint.rs @@ -1,16 +1,8 @@ -use super::CheckpointContentsDigest; -use super::CheckpointDigest; -use super::Digest; -use super::GasCostSummary; -use super::Object; -use super::SignedTransaction; -use super::TransactionDigest; -use super::TransactionEffects; -use super::TransactionEffectsDigest; -use super::TransactionEvents; -use super::UserSignature; -use super::ValidatorAggregatedSignature; -use super::ValidatorCommitteeMember; +use super::{ + CheckpointContentsDigest, CheckpointDigest, Digest, GasCostSummary, Object, SignedTransaction, + TransactionDigest, TransactionEffects, TransactionEffectsDigest, TransactionEvents, + UserSignature, ValidatorAggregatedSignature, ValidatorCommitteeMember, +}; pub type CheckpointSequenceNumber = u64; pub type CheckpointTimestamp = u64; @@ -40,15 +32,16 @@ pub enum CheckpointCommitment { pub struct EndOfEpochData { /// next_epoch_committee is `Some` if and only if the current checkpoint is /// the last checkpoint of an epoch. - /// Therefore next_epoch_committee can be used to pick the last checkpoint of an epoch, - /// which is often useful to get epoch level summary stats like total gas cost of an epoch, - /// or the total number of transactions from genesis to the end of an epoch. - /// The committee is stored as a vector of validator pub key and stake pairs. The vector + /// Therefore next_epoch_committee can be used to pick the last checkpoint + /// of an epoch, which is often useful to get epoch level summary stats + /// like total gas cost of an epoch, or the total number of transactions + /// from genesis to the end of an epoch. The committee is stored as a + /// vector of validator pub key and stake pairs. The vector /// should be sorted based on the Committee data structure. pub next_epoch_committee: Vec, - /// The protocol version that is in effect during the epoch that starts immediately after this - /// checkpoint. + /// The protocol version that is in effect during the epoch that starts + /// immediately after this checkpoint. #[cfg_attr(feature = "serde", serde(with = "crate::_serde::ReadableDisplay"))] #[cfg_attr(feature = "schemars", schemars(with = "crate::_schemars::U64"))] pub next_epoch_protocol_version: ProtocolVersion, @@ -65,24 +58,25 @@ pub struct CheckpointSummary { pub epoch: EpochId, #[cfg_attr(feature = "schemars", schemars(with = "crate::_schemars::U64"))] pub sequence_number: CheckpointSequenceNumber, - /// Total number of transactions committed since genesis, including those in this - /// checkpoint. + /// Total number of transactions committed since genesis, including those in + /// this checkpoint. #[cfg_attr(feature = "schemars", schemars(with = "crate::_schemars::U64"))] pub network_total_transactions: u64, pub content_digest: CheckpointContentsDigest, pub previous_digest: Option, - /// The running total gas costs of all transactions included in the current epoch so far - /// until this checkpoint. + /// The running total gas costs of all transactions included in the current + /// epoch so far until this checkpoint. pub epoch_rolling_gas_cost_summary: GasCostSummary, /// Timestamp of the checkpoint - number of milliseconds from the Unix epoch - /// Checkpoint timestamps are monotonic, but not strongly monotonic - subsequent - /// checkpoints can have same timestamp if they originate from the same underlining consensus commit + /// Checkpoint timestamps are monotonic, but not strongly monotonic - + /// subsequent checkpoints can have same timestamp if they originate + /// from the same underlining consensus commit #[cfg_attr(feature = "schemars", schemars(with = "crate::_schemars::U64"))] pub timestamp_ms: CheckpointTimestamp, - /// Commitments to checkpoint-specific state (e.g. txns in checkpoint, objects read/written in - /// checkpoint). + /// Commitments to checkpoint-specific state (e.g. txns in checkpoint, + /// objects read/written in checkpoint). #[cfg_attr( feature = "schemars", schemars(with = "Option>") @@ -92,9 +86,10 @@ pub struct CheckpointSummary { /// Present only on the final checkpoint of the epoch. pub end_of_epoch_data: Option, - /// CheckpointSummary is not an evolvable structure - it must be readable by any version of the - /// code. Therefore, in order to allow extensions to be added to CheckpointSummary, we allow - /// opaque data to be added to checkpoints which can be deserialized based on the current + /// CheckpointSummary is not an evolvable structure - it must be readable by + /// any version of the code. Therefore, in order to allow extensions to + /// be added to CheckpointSummary, we allow opaque data to be added to + /// checkpoints which can be deserialized based on the current /// protocol version. #[cfg_attr( feature = "schemars", @@ -170,7 +165,8 @@ pub struct CheckpointTransaction { pub effects: TransactionEffects, /// The events, if any, emitted by this transaciton during execution pub events: Option, - /// The state of all inputs to this transaction as they were prior to execution. + /// The state of all inputs to this transaction as they were prior to + /// execution. #[cfg_attr(test, any(proptest::collection::size_range(0..=2).lift()))] pub input_objects: Vec, /// The state of all output objects created or mutated by this transaction. @@ -181,12 +177,9 @@ pub struct CheckpointTransaction { #[cfg(feature = "serde")] #[cfg_attr(doc_cfg, doc(cfg(feature = "serde")))] mod serialization { - use super::*; + use serde::{Deserialize, Deserializer, Serialize, Serializer}; - use serde::Deserialize; - use serde::Deserializer; - use serde::Serialize; - use serde::Serializer; + use super::*; #[derive(serde_derive::Serialize)] struct ReadableCheckpointSummaryRef<'a> { @@ -376,8 +369,7 @@ mod serialization { where S: Serializer, { - use serde::ser::SerializeSeq; - use serde::ser::SerializeTupleVariant; + use serde::ser::{SerializeSeq, SerializeTupleVariant}; if serializer.is_human_readable() { serializer.serialize_newtype_struct("CheckpointContents", &self.0) @@ -546,13 +538,12 @@ mod serialization { #[cfg(test)] mod test { - use super::*; - use base64ct::Base64; - use base64ct::Encoding; - + use base64ct::{Base64, Encoding}; #[cfg(target_arch = "wasm32")] use wasm_bindgen_test::wasm_bindgen_test as test; + use super::*; + #[test] fn signed_checkpoint_fixture() { const FIXTURES: &[&str] = &[ @@ -573,7 +564,7 @@ mod serialization { #[test] fn contents_fixture() { - let fixture ="AAEgp6oAB8Qadn8+FqtdqeDIp8ViQNOZpMKs44MN0N5y7zIgqn5dKR1+8poL0pLNwRo/2knMnodwMTEDhqYL03kdewQBAWEAgpORkfH6ewjfFQYZJhmjkYq0/B3Set4mLJX/G0wUPb/V4H41gJipYu4I6ToyixnEuPQWxHKLckhNn+0UmI+pAJ9GegzEh0q2HWABmFMpFoPw0229dCfzWNOhHW5bes4H"; + let fixture = "AAEgp6oAB8Qadn8+FqtdqeDIp8ViQNOZpMKs44MN0N5y7zIgqn5dKR1+8poL0pLNwRo/2knMnodwMTEDhqYL03kdewQBAWEAgpORkfH6ewjfFQYZJhmjkYq0/B3Set4mLJX/G0wUPb/V4H41gJipYu4I6ToyixnEuPQWxHKLckhNn+0UmI+pAJ9GegzEh0q2HWABmFMpFoPw0229dCfzWNOhHW5bes4H"; let bcs = Base64::decode_vec(fixture).unwrap(); diff --git a/crates/sui-sdk/src/types/crypto/bls12381.rs b/crates/iota-rust-sdk/src/types/crypto/bls12381.rs similarity index 100% rename from crates/sui-sdk/src/types/crypto/bls12381.rs rename to crates/iota-rust-sdk/src/types/crypto/bls12381.rs diff --git a/crates/sui-sdk/src/types/crypto/ed25519.rs b/crates/iota-rust-sdk/src/types/crypto/ed25519.rs similarity index 100% rename from crates/sui-sdk/src/types/crypto/ed25519.rs rename to crates/iota-rust-sdk/src/types/crypto/ed25519.rs diff --git a/crates/sui-sdk/src/types/crypto/mod.rs b/crates/iota-rust-sdk/src/types/crypto/mod.rs similarity index 67% rename from crates/sui-sdk/src/types/crypto/mod.rs rename to crates/iota-rust-sdk/src/types/crypto/mod.rs index c7ee665..3e3d6ea 100644 --- a/crates/sui-sdk/src/types/crypto/mod.rs +++ b/crates/iota-rust-sdk/src/types/crypto/mod.rs @@ -8,54 +8,34 @@ mod signature; mod validator; mod zklogin; -pub use bls12381::Bls12381PrivateKey; -pub use bls12381::Bls12381PublicKey; -pub use bls12381::Bls12381Signature; -pub use ed25519::Ed25519PrivateKey; -pub use ed25519::Ed25519PublicKey; -pub use ed25519::Ed25519Signature; -pub use multisig::MultisigAggregatedSignature; -pub use multisig::MultisigCommittee; -pub use multisig::MultisigMember; -pub use multisig::MultisigMemberPublicKey; -pub use multisig::MultisigMemberSignature; -pub use passkey::PasskeyAuthenticator; -pub use passkey::PasskeyPublicKey; -pub use secp256k1::Secp256k1PrivateKey; -pub use secp256k1::Secp256k1PublicKey; -pub use secp256k1::Secp256k1Signature; -pub use secp256r1::Secp256r1PrivateKey; -pub use secp256r1::Secp256r1PublicKey; -pub use secp256r1::Secp256r1Signature; -pub use signature::SignatureScheme; -pub use signature::SimpleSignature; -pub use signature::UserSignature; -pub use validator::ValidatorAggregatedSignature; -pub use validator::ValidatorCommittee; -pub use validator::ValidatorCommitteeMember; -pub use validator::ValidatorSignature; -pub use zklogin::Bn254FieldElement; -pub use zklogin::CircomG1; -pub use zklogin::CircomG2; -pub use zklogin::Claim; -pub use zklogin::Jwk; -pub use zklogin::JwkId; -pub use zklogin::JwtDetails; -pub use zklogin::ZkLoginAuthenticator; -pub use zklogin::ZkLoginInputs; -pub use zklogin::ZkLoginProof; -pub use zklogin::ZkLoginPublicIdentifier; +pub use bls12381::{Bls12381PrivateKey, Bls12381PublicKey, Bls12381Signature}; +pub use ed25519::{Ed25519PrivateKey, Ed25519PublicKey, Ed25519Signature}; +pub use multisig::{ + MultisigAggregatedSignature, MultisigCommittee, MultisigMember, MultisigMemberPublicKey, + MultisigMemberSignature, +}; +pub use passkey::{PasskeyAuthenticator, PasskeyPublicKey}; +pub use secp256k1::{Secp256k1PrivateKey, Secp256k1PublicKey, Secp256k1Signature}; +pub use secp256r1::{Secp256r1PrivateKey, Secp256r1PublicKey, Secp256r1Signature}; +pub use signature::{SignatureScheme, SimpleSignature, UserSignature}; +pub use validator::{ + ValidatorAggregatedSignature, ValidatorCommittee, ValidatorCommitteeMember, ValidatorSignature, +}; +pub use zklogin::{ + Bn254FieldElement, CircomG1, CircomG2, Claim, Jwk, JwkId, JwtDetails, ZkLoginAuthenticator, + ZkLoginInputs, ZkLoginProof, ZkLoginPublicIdentifier, +}; -// // Implement various base64 fixed-size array helpers // -/// Utility for calculating base64 encoding lenghths. +/// Utility for calculating base64 encoding lengths. /// -/// In the Base64 encoding each character is used to represent 6 bits (log2(64) = 6). This means -/// that 4 characters are used to represnet 4*6 = 24 bits = 3 bytes. So you need 4*(`n`/3) -/// characters in order to represent `n` bytes, and this needs to be rounded up to a multiple of 4. -/// The number of unused padding characters resulting from the rounding will be 0, 1, 2, or 3. +/// In the Base64 encoding each character is used to represent 6 bits (log2(64) +/// = 6). This means that 4 characters are used to represnet 4*6 = 24 bits = 3 +/// bytes. So you need 4*(`n`/3) characters in order to represent `n` bytes, and +/// this needs to be rounded up to a multiple of 4. The number of unused padding +/// characters resulting from the rounding will be 0, 1, 2, or 3. const fn base64_encoded_length(len: usize) -> usize { ((4 * len / 3) + 3) & !3 } @@ -128,13 +108,12 @@ macro_rules! impl_base64_helper { #[cfg(test)] mod $test_module { - use super::$display; - use super::$fromstr; use test_strategy::proptest; - #[cfg(target_arch = "wasm32")] use wasm_bindgen_test::wasm_bindgen_test as test; + use super::{$display, $fromstr}; + #[proptest] fn roundtrip_display_fromstr(array: $fromstr) { let s = $display(&array.0).to_string(); diff --git a/crates/sui-sdk/src/types/crypto/multisig.rs b/crates/iota-rust-sdk/src/types/crypto/multisig.rs similarity index 94% rename from crates/sui-sdk/src/types/crypto/multisig.rs rename to crates/iota-rust-sdk/src/types/crypto/multisig.rs index 4b42927..e43b0eb 100644 --- a/crates/sui-sdk/src/types/crypto/multisig.rs +++ b/crates/iota-rust-sdk/src/types/crypto/multisig.rs @@ -1,12 +1,8 @@ -use super::zklogin::ZkLoginAuthenticator; -use super::zklogin::ZkLoginPublicIdentifier; -use super::Ed25519PublicKey; -use super::Ed25519Signature; -use super::Secp256k1PublicKey; -use super::Secp256k1Signature; -use super::Secp256r1PublicKey; -use super::Secp256r1Signature; -use super::SignatureScheme; +use super::{ + zklogin::{ZkLoginAuthenticator, ZkLoginPublicIdentifier}, + Ed25519PublicKey, Ed25519Signature, Secp256k1PublicKey, Secp256k1Signature, Secp256r1PublicKey, + Secp256r1Signature, SignatureScheme, +}; pub type WeightUnit = u8; pub type ThresholdUnit = u16; @@ -59,7 +55,8 @@ pub struct MultisigCommittee { /// A list of committee members and their corresponding weight. #[cfg_attr(test, any(proptest::collection::size_range(0..=10).lift()))] members: Vec, - /// If the total weight of the public keys corresponding to verified signatures is larger than threshold, the Multisig is verified. + /// If the total weight of the public keys corresponding to verified + /// signatures is larger than threshold, the Multisig is verified. threshold: ThresholdUnit, } @@ -77,7 +74,8 @@ impl MultisigCommittee { } } -/// The struct that contains signatures and public keys necessary for authenticating a Multisig. +/// The struct that contains signatures and public keys necessary for +/// authenticating a Multisig. #[derive(Debug, Clone)] #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] #[cfg_attr(test, derive(test_strategy::Arbitrary))] @@ -85,10 +83,11 @@ pub struct MultisigAggregatedSignature { /// The plain signature encoded with signature scheme. #[cfg_attr(test, any(proptest::collection::size_range(0..=10).lift()))] signatures: Vec, - /// A bitmap that indicates the position of which public key the signature should be authenticated with. + /// A bitmap that indicates the position of which public key the signature + /// should be authenticated with. bitmap: BitmapUnit, /// Legacy encoding for the bitmap. - //TODO implement a strategy for legacy bitmap + // TODO implement a strategy for legacy bitmap #[cfg_attr( feature = "schemars", schemars( @@ -98,7 +97,8 @@ pub struct MultisigAggregatedSignature { )] #[cfg_attr(test, strategy(proptest::strategy::Just(None)))] legacy_bitmap: Option, - /// The public key encoded with each public key with its signature scheme used along with the corresponding weight. + /// The public key encoded with each public key with its signature scheme + /// used along with the corresponding weight. committee: MultisigCommittee, } @@ -122,7 +122,8 @@ impl MultisigAggregatedSignature { impl PartialEq for MultisigAggregatedSignature { fn eq(&self, other: &Self) -> bool { - // Skip comparing the legacy bitmap since we always convert to the new bitmap form + // Skip comparing the legacy bitmap since we always convert to the new bitmap + // form self.bitmap == other.bitmap && self.signatures == other.signatures && self.committee == other.committee @@ -157,24 +158,18 @@ pub enum MultisigMemberSignature { #[cfg(feature = "serde")] #[cfg_attr(doc_cfg, doc(cfg(feature = "serde")))] mod serialization { - use super::*; - use crate::types::crypto::Base64Array33; - use crate::types::crypto::Base64Array34; - use crate::types::Ed25519PublicKey; - use crate::types::Secp256k1PublicKey; - use crate::types::Secp256r1PublicKey; - use crate::types::SignatureScheme; - use base64ct::Base64; - use base64ct::Encoding; - use serde::Deserialize; - use serde::Deserializer; - use serde::Serialize; - use serde::Serializer; - use serde_with::Bytes; - use serde_with::DeserializeAs; - use serde_with::SerializeAs; use std::borrow::Cow; + use base64ct::{Base64, Encoding}; + use serde::{Deserialize, Deserializer, Serialize, Serializer}; + use serde_with::{Bytes, DeserializeAs, SerializeAs}; + + use super::*; + use crate::types::{ + crypto::{Base64Array33, Base64Array34}, + Ed25519PublicKey, Secp256k1PublicKey, Secp256r1PublicKey, SignatureScheme, + }; + pub struct Base64MultisigMemberPublicKey; impl SerializeAs for Base64MultisigMemberPublicKey { @@ -221,7 +216,7 @@ mod serialization { let flag = SignatureScheme::from_byte( *bytes .first() - .ok_or_else(|| serde::de::Error::custom("missing signature scheme falg"))?, + .ok_or_else(|| serde::de::Error::custom("missing signature scheme flag"))?, ) .map_err(serde::de::Error::custom)?; let public_key_bytes = &bytes[1..]; @@ -428,7 +423,7 @@ mod serialization { let flag = SignatureScheme::from_byte( *bytes .first() - .ok_or_else(|| serde::de::Error::custom("missing signature scheme falg"))?, + .ok_or_else(|| serde::de::Error::custom("missing signature scheme flag"))?, ) .map_err(serde::de::Error::custom)?; if flag != SignatureScheme::Multisig { @@ -436,9 +431,9 @@ mod serialization { } let bcs_bytes = &bytes[1..]; - // Unfortunately we have no information in the serialized form of a Multisig to be - // able to determine if its a Legacy format or the new standard format so we just - // need to try each. + // Unfortunately we have no information in the serialized form of a Multisig to + // be able to determine if its a Legacy format or the new standard + // format so we just need to try each. // // We'll start with the newer format as that should be more prevalent. if let Ok(multisig) = bcs::from_bytes::(bcs_bytes) { diff --git a/crates/sui-sdk/src/types/crypto/passkey.rs b/crates/iota-rust-sdk/src/types/crypto/passkey.rs similarity index 83% rename from crates/sui-sdk/src/types/crypto/passkey.rs rename to crates/iota-rust-sdk/src/types/crypto/passkey.rs index 707e0ad..9a6fad9 100644 --- a/crates/sui-sdk/src/types/crypto/passkey.rs +++ b/crates/iota-rust-sdk/src/types/crypto/passkey.rs @@ -1,8 +1,8 @@ -use crate::types::Digest; - use super::{Secp256r1PublicKey, Secp256r1Signature}; +use crate::types::Digest; -/// An passkey authenticator with parsed fields. See field defition below. Can be initialized from [struct RawPasskeyAuthenticator]. +/// An passkey authenticator with parsed fields. See field definition below. Can +/// be initialized from [struct RawPasskeyAuthenticator]. #[derive(Debug, Clone, PartialEq, Eq)] pub struct PasskeyAuthenticator { /// Compact r1 public key upon passkey creation. @@ -13,10 +13,12 @@ pub struct PasskeyAuthenticator { /// Initialized from `user_signature` in `RawPasskeyAuthenticator`. signature: Secp256r1Signature, - /// Valid intent parsed from the first 3 bytes of `client_data_json.challenge`. + /// Valid intent parsed from the first 3 bytes of + /// `client_data_json.challenge`. intent: [u8; 3], - /// Valid tx_digest parsed from the last 32 bytes of `client_data_json.challenge`. + /// Valid tx_digest parsed from the last 32 bytes of + /// `client_data_json.challenge`. digest: Digest, /// `authenticatorData` is a bytearray that encodes @@ -45,17 +47,13 @@ impl PasskeyPublicKey { #[cfg(feature = "serde")] #[cfg_attr(doc_cfg, doc(cfg(feature = "serde")))] mod serialization { - use crate::types::SignatureScheme; - use crate::types::SimpleSignature; + use std::borrow::Cow; + + use serde::{Deserialize, Deserializer, Serialize, Serializer}; + use serde_with::{Bytes, DeserializeAs}; use super::*; - use serde::Deserialize; - use serde::Deserializer; - use serde::Serialize; - use serde::Serializer; - use serde_with::Bytes; - use serde_with::DeserializeAs; - use std::borrow::Cow; + use crate::types::{SignatureScheme, SimpleSignature}; #[derive(serde::Serialize)] struct AuthenticatorRef<'a> { @@ -199,19 +197,21 @@ mod serialization { } } - /// The client data represents the contextual bindings of both the Relying Party and the client. - /// It is a key-value mapping whose keys are strings. Values can be any type that has a valid - /// encoding in JSON. + /// The client data represents the contextual bindings of both the Relying + /// Party and the client. It is a key-value mapping whose keys are + /// strings. Values can be any type that has a valid encoding in JSON. /// - /// > Note: The [`CollectedClientData`] may be extended in the future. Therefore it’s critical when - /// > parsing to be tolerant of unknown keys and of any reordering of the keys + /// > Note: The [`CollectedClientData`] may be extended in the future. + /// > Therefore it’s critical when + /// > parsing to be tolerant of unknown keys and of any reordering of the + /// > keys /// - /// This struct conforms to the JSON byte serialization format expected of `CollectedClientData`, - /// detailed in section [5.8.1.1 Serialization] of the WebAuthn spec. Namely the following - /// requirements: + /// This struct conforms to the JSON byte serialization format expected of + /// `CollectedClientData`, detailed in section [5.8.1.1 Serialization] + /// of the WebAuthn spec. Namely the following requirements: /// - /// * `type`, `challenge`, `origin`, `crossOrigin` must always be present in the serialized format - /// _in that order_. + /// * `type`, `challenge`, `origin`, `crossOrigin` must always be present in + /// the serialized format _in that order_. /// /// /// @@ -219,44 +219,51 @@ mod serialization { #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct CollectedClientData { - /// This member contains the value [`ClientDataType::Create`] when creating new credentials, and - /// [`ClientDataType::Get`] when getting an assertion from an existing credential. The purpose - /// of this member is to prevent certain types of signature confusion attacks (where an attacker - /// substitutes one legitimate signature for another). + /// This member contains the value [`ClientDataType::Create`] when + /// creating new credentials, and [`ClientDataType::Get`] when + /// getting an assertion from an existing credential. The purpose + /// of this member is to prevent certain types of signature confusion + /// attacks (where an attacker substitutes one legitimate + /// signature for another). #[serde(rename = "type")] pub ty: ClientDataType, - /// This member contains the base64url encoding of the challenge provided by the Relying Party. - /// See the [Cryptographic Challenges] security consideration. + /// This member contains the base64url encoding of the challenge + /// provided by the Relying Party. See the [Cryptographic + /// Challenges] security consideration. /// /// [Cryptographic Challenges]: https://w3c.github.io/webauthn/#sctn-cryptographic-challenges /// /// https://w3c.github.io/webauthn/#base64url-encoding /// - /// The term Base64url Encoding refers to the base64 encoding using the URL- and filename-safe - /// character set defined in Section 5 of [RFC4648], with all trailing '=' characters omitted - /// (as permitted by Section 3.2) and without the inclusion of any line breaks, whitespace, or - /// other additional characters. + /// The term Base64url Encoding refers to the base64 encoding using the + /// URL- and filename-safe character set defined in Section 5 of + /// [RFC4648], with all trailing '=' characters omitted + /// (as permitted by Section 3.2) and without the inclusion of any line + /// breaks, whitespace, or other additional characters. pub challenge: String, - /// This member contains the fully qualified origin of the requester, as provided to the - /// authenticator by the client, in the syntax defined by [RFC6454]. + /// This member contains the fully qualified origin of the requester, as + /// provided to the authenticator by the client, in the syntax + /// defined by [RFC6454]. /// /// [RFC6454]: https://www.rfc-editor.org/rfc/rfc6454 pub origin: String, - // /// This OPTIONAL member contains the inverse of the sameOriginWithAncestors argument value that - // /// was passed into the internal method + // /// This OPTIONAL member contains the inverse of the sameOriginWithAncestors argument + // value that /// was passed into the internal method // #[serde(default, serialize_with = "truthiness")] // #[serde(rename = "type")] // pub cross_origin: Option, } - /// Used to limit the values of [`CollectedClientData::ty`] and serializes to static strings. + /// Used to limit the values of [`CollectedClientData::ty`] and serializes + /// to static strings. #[derive(Debug, Deserialize, Serialize, Clone, Copy, PartialEq, Eq)] pub enum ClientDataType { /// Serializes to the string `"webauthn.get"` /// - /// Passkey's in Sui only support the value `"webauthn.get"`, other values will be rejected. + /// Passkey's in Iota only support the value `"webauthn.get"`, other + /// values will be rejected. #[serde(rename = "webauthn.get")] Get, // /// Serializes to the string `"webauthn.create"` @@ -278,8 +285,7 @@ impl proptest::arbitrary::Arbitrary for PasskeyAuthenticator { fn arbitrary_with(_args: Self::Parameters) -> Self::Strategy { use proptest::{collection::vec, prelude::*}; - use serialization::ClientDataType; - use serialization::CollectedClientData; + use serialization::{ClientDataType, CollectedClientData}; ( any::(), diff --git a/crates/sui-sdk/src/types/crypto/secp256k1.rs b/crates/iota-rust-sdk/src/types/crypto/secp256k1.rs similarity index 100% rename from crates/sui-sdk/src/types/crypto/secp256k1.rs rename to crates/iota-rust-sdk/src/types/crypto/secp256k1.rs diff --git a/crates/sui-sdk/src/types/crypto/secp256r1.rs b/crates/iota-rust-sdk/src/types/crypto/secp256r1.rs similarity index 100% rename from crates/sui-sdk/src/types/crypto/secp256r1.rs rename to crates/iota-rust-sdk/src/types/crypto/secp256r1.rs diff --git a/crates/sui-sdk/src/types/crypto/signature.rs b/crates/iota-rust-sdk/src/types/crypto/signature.rs similarity index 96% rename from crates/sui-sdk/src/types/crypto/signature.rs rename to crates/iota-rust-sdk/src/types/crypto/signature.rs index 85e7f7a..a2b3b45 100644 --- a/crates/sui-sdk/src/types/crypto/signature.rs +++ b/crates/iota-rust-sdk/src/types/crypto/signature.rs @@ -1,12 +1,8 @@ -use super::Ed25519PublicKey; -use super::Ed25519Signature; -use super::MultisigAggregatedSignature; -use super::PasskeyAuthenticator; -use super::Secp256k1PublicKey; -use super::Secp256k1Signature; -use super::Secp256r1PublicKey; -use super::Secp256r1Signature; -use super::ZkLoginAuthenticator; +use super::{ + Ed25519PublicKey, Ed25519Signature, MultisigAggregatedSignature, PasskeyAuthenticator, + Secp256k1PublicKey, Secp256k1Signature, Secp256r1PublicKey, Secp256r1Signature, + ZkLoginAuthenticator, +}; #[derive(Clone, Debug, PartialEq, Eq, Hash)] #[cfg_attr( @@ -48,7 +44,7 @@ impl SimpleSignature { let flag = SignatureScheme::from_byte( *bytes .first() - .ok_or_else(|| serde::de::Error::custom("missing signature scheme falg"))?, + .ok_or_else(|| serde::de::Error::custom("missing signature scheme flag"))?, ) .map_err(serde::de::Error::custom)?; match flag { @@ -509,7 +505,7 @@ mod serialization { serde_with::Bytes::deserialize_as(deserializer)?; let flag = SignatureScheme::from_byte(*bytes.first().ok_or_else(|| { - serde::de::Error::custom("missing signature scheme falg") + serde::de::Error::custom("missing signature scheme flag") })?) .map_err(serde::de::Error::custom)?; match flag { @@ -541,14 +537,13 @@ mod serialization { #[cfg(test)] mod test { - use super::*; - use base64ct::Base64; - use base64ct::Encoding; + use base64ct::{Base64, Encoding}; use test_strategy::proptest; - #[cfg(target_arch = "wasm32")] use wasm_bindgen_test::wasm_bindgen_test as test; + use super::*; + #[proptest] fn roundtrip_signature_scheme(scheme: SignatureScheme) { assert_eq!(Ok(scheme), SignatureScheme::from_byte(scheme.to_u8())); @@ -556,10 +551,19 @@ mod serialization { #[test] fn simple_fixtures() { - const FIXTURES: &[(SignatureScheme, &str)] = &[ - (SignatureScheme::Ed25519, "YQDaeO4w2ULMy5eqHBzP0oalr1YhDX/9uJS9MntKnW3d55q4aqZYYnoEloaBmXKc6FoD5bTwONdwS9CwdMQGhIcPDX2rNYyNrapO+gBJp1sHQ2VVsQo2ghm7aA9wVxNJ13U="), - (SignatureScheme::Secp256k1, "YgErcT6WUSQXGD1DaIwls5rWq648akDMlvL41ugUUhyIPWnqURl+daQLG+ILNemARKHYVNOikKJJ8jqu+HzlRa5rAg4XzVk55GsZZkGWjNdZkQuiV34n+nP944dtub7FvOsr"), - (SignatureScheme::Secp256r1, "YgLp1p4K9dSQTt2AeR05yK1MkXmtLm6Sieb9yfkpW1gOBiqnO9ZKZiWUrLJQav2Mxw64zM37g3IVdsB/To6qfl8IA0f7ryPwOKvEwwiicRF6Kkz/rt28X/gcdRe8bHSn7bQw"), + const FIXTURES: &[(SignatureScheme, &str)] = &[ + ( + SignatureScheme::Ed25519, + "YQDaeO4w2ULMy5eqHBzP0oalr1YhDX/9uJS9MntKnW3d55q4aqZYYnoEloaBmXKc6FoD5bTwONdwS9CwdMQGhIcPDX2rNYyNrapO+gBJp1sHQ2VVsQo2ghm7aA9wVxNJ13U=", + ), + ( + SignatureScheme::Secp256k1, + "YgErcT6WUSQXGD1DaIwls5rWq648akDMlvL41ugUUhyIPWnqURl+daQLG+ILNemARKHYVNOikKJJ8jqu+HzlRa5rAg4XzVk55GsZZkGWjNdZkQuiV34n+nP944dtub7FvOsr", + ), + ( + SignatureScheme::Secp256r1, + "YgLp1p4K9dSQTt2AeR05yK1MkXmtLm6Sieb9yfkpW1gOBiqnO9ZKZiWUrLJQav2Mxw64zM37g3IVdsB/To6qfl8IA0f7ryPwOKvEwwiicRF6Kkz/rt28X/gcdRe8bHSn7bQw", + ), ]; for (scheme, fixture) in FIXTURES { @@ -634,7 +638,7 @@ mod serialization { #[test] fn zklogin_fixtures() { - const FIXTURES: &[&str] = &[ + const FIXTURES: &[&str] = &[ "mAcFA00yMTM0MzA3MTg2NDQ3ODc4NTU1OTU1OTY2Njg3NDQ3Njg0MzYyODQxNjA4OTQ4ODEyMTk4MjQ0OTY0ODk4OTg3OTkxMTI1MTY2OTA2N0w1MzYyMzAzOTQxMzk3NzQ1MTk2MTQxNjgxNjA5MDk0MDI4MTg3NzgxMzY2ODc3ODA5NTA2NTU0NzA3MjQ4MzcwNzM4OTcwOTI5MzYwATEDAk0xOTAzMjkyNDMyMDAxODEyNjcyNzEyMDYzMjYzMzM2OTE1NTg2MDc4NDA0NjY2MDcyMzIzMjU0MTAwMjQyODAxODA4ODQ4MTI3MzA5N0sxOTM0MDEzODQwOTcyNjc5OTM0MzgxMTI2ODg3OTQ2MTk1NDk5NTczMjY3NTE5ODAxNDA4MzQ2MzA3NDA2NzI3NjIxNzI0MTA4ODUCTDQxMTc0OTU3NjIwNzc2NjE4OTk2Njk5ODU1MTUzMzc2MDcwMTkzNTgwMjc2MjUxNTc4MDQwMTc0NTI2OTM1MTY5ODY1MDU1NDcyMTdNMTI3MDM0MzkzNTYyNTQ3NTM4NDA5NzAxMjA3MDAxMjM5MjcxOTU1OTI4OTE0MDgxMzY5NzQ0ODkwMzkzMzgyOTgzODYwODQxODYyNzYCATEBMANMNjAyNTg2MDg4MjI2OTUxNTE2NDY3MjY1NjU3OTU4MDE1OTMyMTI2ODY4MDM1NjU0NTkxOTA1NDkwNzkzNTM4MzY1NDYwNzA5MTIyOE0xNTUxNzY4ODA2NDc3NTgzMDI3NzAwNjY2NzE2OTM2NzAxNjU4Nzk5NDIyNjc1MTQ0Nzg5ODMzNjg0MDk5NjU4MDczNzg0NDY0NDExNQExMXdpYVhOeklqb2lhSFIwY0hNNkx5OXBaQzUwZDJsMFkyZ3VkSFl2YjJGMWRHZ3lJaXcCMmV5SmhiR2NpT2lKU1V6STFOaUlzSW5SNWNDSTZJa3BYVkNJc0ltdHBaQ0k2SWpFaWZRTDIwMjIzNjc3MTc2ODYwNzEyNzk5MTIwNjA0MTY1NTc3MDEyMjMyOTk3NTc0MjQwNjg2MDUwMzc1OTc1MTI1NzUzNDA0NDU0MTY4MTAKAAAAAAAAAGICUv1c+GW7/G0rKAO5QgQrqs3ujZALi4GWTkqgEjfTqMs53H1MeeRJdWzJW104/97F1VJyjm01ozKRasbRJGSsRwKi14vTFJZpnOkPlaKtNt4cGpY4PpaoeXb289IzLDx1Gg==", "mwcFA00xMDE2MjI2MTYwOTg0NDYxNDI1OTY3MjA3OTg1MTYyNzUxNTQyNjEzMzM1OTEzMTc5NDQ3ODc4MDgzNDA3NTkxNDc5ODcxNzMzNzUzNU0xNjUwMTEzNTg2OTk2NDUwMDk1Njk2MDE2NzI0NzgwMzY3MzkyNDI4NDI0NTU3MDIyODMyODc4MDYxNjE4NzE0MzY2MzgzNzA0MjMyNAExAwJMNjAyMjIxMDk3ODA0MDA5MTgyMjQ1MDM2NjM2NjkyMzE1Mjg2NDAzMDQzNjY2ODg5NTUzNzYwNTM5MTM4MDA3OTAxMzIzMjE5OTk2NU0xNjEwNjE0MDY4NzEwMDc3MzQyNDIyNTI0NjEyNzM3ODIyNTgwOTIxMTQxMTYwMjQzMTIwMzI3NDM2MjM1NjEwOTI5NDk5Mjg2MjM4NgJMNzQwNDE3NTg3NDgyOTU3NDM0NTk1NDk1MTU0NDkxODY2ODI5ODQ0OTYxNjMzMDAyMzE4MzE4MzcwMTgxNjEwOTg3OTAwOTY5MTcxMUw3MzAwNzMwODk0MDQzNjM0NjI0NzIwNzkzNDIxNTM1NTUxODI3NDU4NjE4NzU5NjE2OTEzMjU0ODY4MzUzODE1MzM5ODg3MjIzMTA5AgExATADTTExNDA2NTA2NzUyNTkyODQ5NDk4MzcyNzYxODIyNzM4MjA2NTY0ODc4ODM3NTE3NzkxNTY2MzQ3NDk0NDkyNDQyMTI4MDExMTQwMzU3TTE1Njk5MzYzODA5ODg4MDc3MDcxNjM1NTg1MTA2NzA2MjE0NTcxMDI3NDU3ODE5MTE4NTE1NTk2MjA4MDgzODUzODcyOTM3NzQxNDczATExd2lhWE56SWpvaWFIUjBjSE02THk5cFpDNTBkMmwwWTJndWRIWXZiMkYxZEdneUlpdwIyZXlKaGJHY2lPaUpTVXpJMU5pSXNJblI1Y0NJNklrcFhWQ0lzSW10cFpDSTZJakVpZlFNMTc1NzI2MTY4NDgyNzU4OTMzODIyMTc0ODE3OTM5MTkwMDYzNjYzNzY4NTk4MTcwNDA1NDYwNDk4MzU5NTgxODc0NjEyOTg2NjkyNzAKAAAAAAAAAGICl9lwjktCQkH7GqGGV6EdbjHv4Go6MIDmr6EIvtg/2h5IuXKJF5GoVLuykxWwkSdNr9iRUZaz3Z0p/Z9nPJlW/gNaiwdVCMdfShJHSZgqfSH4DZpfaJPkGp6VX+TIIeDevg==", "mgcFA00xOTUwNDI1NDE5MzgxMzM3OTA5NDA1MzkyODkyNTQwMjAxMjIxMTg4ODY5MDAzOTQ3ODM0MjYzOTk4OTcwMjA4MjAxNjY2MDkyNzg4MU0xODEwMjYxODU0NjY0NjY3MDgyMjI5MjczMjIwMDgzMzU0OTk4NDAxMTkxMDI1MDY2MjQ4Mjk5MjMzODgzNjA1NTc1MzMyNTUyMTUzMwExAwJMNTI0MzA1OTQ2MTI1NDQxOTM0NzgzOTMxMjI4ODQ5NjY4OTI0Njk4NzIyMTMyMDcxMDcyNzc2NzgzNzc3NDc4ODI4Mzc1NjgzMTAyOE0xMjA3MDIwMzk2MzAzNjY0NTY2NjAyMzUwNDMyNDM3NDY1OTYwMTY1NzY2NDAzOTU4MzE0MDU2Njc2MDExOTcwMTA3MjI5MjA0NzkxMQJNMTYzNjc2NDUxMTMxNzA1OTkxMTgwNzc1NjgxOTUyMjA5ODY1NjcxNjE0ODk2MDcyNDI1NzQ2ODg5ODQ0NzI4NTk0MzE2Mzk4MzQxNzhMNTg5MTQ4MzY3MjI1MTQyMzgzODE5NTQxNDg0NjEwNTY0Nzk4MDE2NjAyODIyNjcwMzE2ODE1Njg2MzkzNjUxNjk1OTkzMjE4MzExNQIBMQEwA0w2NDc2MTA0MzAwODgxNTQ2NTk3NjUwODk0NjEzNTUyMDc1NDg4Mjk5NjA4NjM5MTY4MzE3MjgzNTg2ODI3MDA3MTUzODg5MjI1MTI2TDQ3NjgzNjQxMTE1NjM0NzI0MDI1NzA4NDE0ODEyMDMzMTgzMDQzMTQ1MDQ4NjcxMzk1NzQ0MzAzODI2NzA4MDcwMTkwNDgxMTQyNzEBMTF3aWFYTnpJam9pYUhSMGNITTZMeTlwWkM1MGQybDBZMmd1ZEhZdmIyRjFkR2d5SWl3AjJleUpoYkdjaU9pSlNVekkxTmlJc0luUjVjQ0k2SWtwWFZDSXNJbXRwWkNJNklqRWlmUU0xMDc0MzE4MDg0MjY5ODE2Mzk0ODQ5NzAyMjkwMDE0Mzc4NjI0MTEwOTYyMzMyMDgzNzYxNzUzMDY5NzUxNDA1MzIwODA1NjEwNzgzNAoAAAAAAAAAYgLL7Jn3QV4USqVbuv97w4LqA12BAwU95fsUrvymgAUPtiepsG6kCVnX903PFZBusNM07tgWJ4/5ypb5mbJQhijJA+3BG7HM6kM2jZ0NPldx4AR5zvu+l4ZXRC4lo39h/K5s", @@ -658,7 +662,7 @@ mod serialization { #[test] fn passkey_fixtures() { - const FIXTURES: &[&str] = &[ + const FIXTURES: &[&str] = &[ "lgIGJUmWDeWIDoxodDQXD2R2YFuP5K65ooYyx5lc87qDHZdjHQAAAACKAXsidHlwZSI6IndlYmF1dGhuLmdldCIsImNoYWxsZW5nZSI6IkFBQUF0X21qSUIxdmJWcFlNNldWNllfb2l4Nko4YU5fOXNiOFNLRmJ1a0JmaVF3Iiwib3JpZ2luIjoiaHR0cDovL2xvY2FsaG9zdDo1MTczIiwiY3Jvc3NPcmlnaW4iOmZhbHNlfWICmOyQv1fJ+inKD0C/sxKtxyFKl9aoBign6p9Ih3iA2ahDVg2CPZqUOlEhur2S2GbIZjbn6TbgWtbXXg8SjLkL7wM9Fw4JO0AKLdnLC1nhQguHBX5K6Hv2ta1sqoOqEFDDEw==", ]; diff --git a/crates/sui-sdk/src/types/crypto/validator.rs b/crates/iota-rust-sdk/src/types/crypto/validator.rs similarity index 94% rename from crates/sui-sdk/src/types/crypto/validator.rs rename to crates/iota-rust-sdk/src/types/crypto/validator.rs index bf678e2..12a36da 100644 --- a/crates/sui-sdk/src/types/crypto/validator.rs +++ b/crates/iota-rust-sdk/src/types/crypto/validator.rs @@ -1,7 +1,5 @@ -use super::Bls12381PublicKey; -use super::Bls12381Signature; -use crate::types::checkpoint::EpochId; -use crate::types::checkpoint::StakeUnit; +use super::{Bls12381PublicKey, Bls12381Signature}; +use crate::types::checkpoint::{EpochId, StakeUnit}; #[derive(Clone, Debug, PartialEq, Eq)] #[cfg_attr( @@ -62,8 +60,8 @@ type RoaringBitMapSerialization = ::serde_with::As< >, >; -// Similar to Digest...unfortunately validator's public key material is serialized with the length -// (96) prefixed +// Similar to Digest...unfortunately validator's public key material is +// serialized with the length (96) prefixed #[cfg(feature = "serde")] type ValidatorPublicKeySerialization = ::serde_with::As< ::serde_with::IfIsHumanReadable<::serde_with::DisplayFromStr, BinaryValidatorPublicKey>, @@ -113,16 +111,15 @@ pub struct ValidatorSignature { #[cfg(test)] mod test { - use super::*; - #[cfg(target_arch = "wasm32")] use wasm_bindgen_test::wasm_bindgen_test as test; + use super::*; + #[cfg(feature = "serde")] #[test] fn aggregated_signature_fixture() { - use base64ct::Base64; - use base64ct::Encoding; + use base64ct::{Base64, Encoding}; const FIXTURE: &str = "CgAAAAAAAACZrBcXiqa0ttztfwrBxKzQRzIRnZhbmsQV7tqNXwiZQrRC+dVDbdua1Ety9uy2pCUSOjAAAAEAAAAAAAAAEAAAAAAA"; let bcs = Base64::decode_vec(FIXTURE).unwrap(); diff --git a/crates/sui-sdk/src/types/crypto/zklogin.rs b/crates/iota-rust-sdk/src/types/crypto/zklogin.rs similarity index 95% rename from crates/sui-sdk/src/types/crypto/zklogin.rs rename to crates/iota-rust-sdk/src/types/crypto/zklogin.rs index 3d462dc..826c683 100644 --- a/crates/sui-sdk/src/types/crypto/zklogin.rs +++ b/crates/iota-rust-sdk/src/types/crypto/zklogin.rs @@ -1,6 +1,5 @@ use super::SimpleSignature; -use crate::types::checkpoint::EpochId; -use crate::types::u256::U256; +use crate::types::{checkpoint::EpochId, u256::U256}; /// An zk login authenticator with all the necessary fields. #[derive(Debug, Clone, PartialEq, Eq)] @@ -13,7 +12,8 @@ pub struct ZkLoginAuthenticator { signature: SimpleSignature, } -/// All inputs required for the zk login proof verification and other public inputs. +/// All inputs required for the zk login proof verification and other public +/// inputs. #[derive(Debug, Clone, PartialEq, Eq)] #[cfg_attr( feature = "serde", @@ -43,7 +43,7 @@ pub struct Claim { index_mod_4: u8, } -/// A structed of parsed JWT details, consists of kid, header, iss. +/// A structured of parsed JWT details, consists of kid, header, iss. #[derive(Default, Debug, Clone, PartialEq, Eq)] #[cfg_attr( feature = "serde", @@ -71,16 +71,16 @@ pub struct ZkLoginProof { c: CircomG1, } -/// A G1 point in BN254 serialized as a vector of three strings which is the canonical decimal -/// representation of the projective coordinates in Fq. +/// A G1 point in BN254 serialized as a vector of three strings which is the +/// canonical decimal representation of the projective coordinates in Fq. #[derive(Clone, Debug, PartialEq, Eq)] #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] #[cfg_attr(test, derive(test_strategy::Arbitrary))] pub struct CircomG1([Bn254FieldElement; 3]); -/// A G2 point in BN254 serialized as a vector of three vectors each being a vector of two strings -/// which are the canonical decimal representation of the coefficients of the projective coordinates -/// in Fq2. +/// A G2 point in BN254 serialized as a vector of three vectors each being a +/// vector of two strings which are the canonical decimal representation of the +/// coefficients of the projective coordinates in Fq2. #[derive(Clone, Debug, PartialEq, Eq)] #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] #[cfg_attr(test, derive(test_strategy::Arbitrary))] @@ -91,7 +91,7 @@ pub struct CircomG2([[Bn254FieldElement; 2]; 3]); #[derive(Clone, Debug, PartialEq, Eq)] #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] #[cfg_attr(test, derive(test_strategy::Arbitrary))] -//TODO ensure iss is less than 255 bytes long +// TODO ensure iss is less than 255 bytes long pub struct ZkLoginPublicIdentifier { iss: String, address_seed: Bn254FieldElement, @@ -202,15 +202,16 @@ impl std::str::FromStr for Bn254FieldElement { #[cfg(test)] mod test { - use super::Bn254FieldElement; + use std::str::FromStr; + use num_bigint::BigUint; use proptest::prelude::*; - use std::str::FromStr; use test_strategy::proptest; - #[cfg(target_arch = "wasm32")] use wasm_bindgen_test::wasm_bindgen_test as test; + use super::Bn254FieldElement; + #[test] fn unpadded_slice() { let seed = Bn254FieldElement([0; 32]); @@ -250,19 +251,16 @@ mod test { #[cfg(feature = "serde")] #[cfg_attr(doc_cfg, doc(cfg(feature = "serde")))] mod serialization { - use crate::types::SignatureScheme; + use std::borrow::Cow; + + use serde::{Deserialize, Deserializer, Serialize, Serializer}; + use serde_with::{Bytes, DeserializeAs, SerializeAs}; use super::*; - use serde::Deserialize; - use serde::Deserializer; - use serde::Serialize; - use serde::Serializer; - use serde_with::Bytes; - use serde_with::DeserializeAs; - use serde_with::SerializeAs; - use std::borrow::Cow; + use crate::types::SignatureScheme; - // Serialized format is: iss_bytes_len || iss_bytes || padded_32_byte_address_seed. + // Serialized format is: iss_bytes_len || iss_bytes || + // padded_32_byte_address_seed. impl Serialize for ZkLoginPublicIdentifier { fn serialize(&self, serializer: S) -> Result where @@ -401,7 +399,7 @@ mod serialization { let flag = SignatureScheme::from_byte( *bytes .first() - .ok_or_else(|| serde::de::Error::custom("missing signature scheme falg"))?, + .ok_or_else(|| serde::de::Error::custom("missing signature scheme flag"))?, ) .map_err(serde::de::Error::custom)?; if flag != SignatureScheme::ZkLogin { diff --git a/crates/sui-sdk/src/types/digest.rs b/crates/iota-rust-sdk/src/types/digest.rs similarity index 97% rename from crates/sui-sdk/src/types/digest.rs rename to crates/iota-rust-sdk/src/types/digest.rs index 752acd2..c367e1f 100644 --- a/crates/sui-sdk/src/types/digest.rs +++ b/crates/iota-rust-sdk/src/types/digest.rs @@ -48,7 +48,7 @@ impl Digest { bs58::decode(base58) .onto(&mut buf) - //TODO fix error to contain bs58 parse error + // TODO fix error to contain bs58 parse error .map_err(|_| DigestParseError)?; Ok(Self(buf)) @@ -133,8 +133,9 @@ impl std::fmt::LowerHex for Digest { } } -// Unfortunately sui's binary representation of digests is prefixed with its length meaning its -// serialized binary form is 33 bytes long (in bcs) vs a more compact 32 bytes. +// Unfortunately iota's binary representation of digests is prefixed with its +// length meaning its serialized binary form is 33 bytes long (in bcs) vs a more +// compact 32 bytes. #[cfg(feature = "serde")] type DigestSerialization = ::serde_with::As<::serde_with::IfIsHumanReadable>; @@ -182,7 +183,6 @@ impl std::fmt::Display for DigestParseError { impl std::error::Error for DigestParseError {} -// // Implement Various Digest wrappers // @@ -317,12 +317,12 @@ impl_digest!(EffectsAuxiliaryDataDigest); #[cfg(test)] mod test { - use super::*; use test_strategy::proptest; - #[cfg(target_arch = "wasm32")] use wasm_bindgen_test::wasm_bindgen_test as test; + use super::*; + #[proptest] fn roundtrip_display_fromstr(digest: Digest) { let s = digest.to_string(); diff --git a/crates/sui-sdk/src/types/effects/fixtures/genesis-transaction-effects b/crates/iota-rust-sdk/src/types/effects/fixtures/genesis-transaction-effects similarity index 100% rename from crates/sui-sdk/src/types/effects/fixtures/genesis-transaction-effects rename to crates/iota-rust-sdk/src/types/effects/fixtures/genesis-transaction-effects diff --git a/crates/sui-sdk/src/types/effects/fixtures/pyth-wormhole-v2 b/crates/iota-rust-sdk/src/types/effects/fixtures/pyth-wormhole-v2 similarity index 100% rename from crates/sui-sdk/src/types/effects/fixtures/pyth-wormhole-v2 rename to crates/iota-rust-sdk/src/types/effects/fixtures/pyth-wormhole-v2 diff --git a/crates/sui-sdk/src/types/effects/mod.rs b/crates/iota-rust-sdk/src/types/effects/mod.rs similarity index 86% rename from crates/sui-sdk/src/types/effects/mod.rs rename to crates/iota-rust-sdk/src/types/effects/mod.rs index 65866a7..bd72539 100644 --- a/crates/sui-sdk/src/types/effects/mod.rs +++ b/crates/iota-rust-sdk/src/types/effects/mod.rs @@ -1,17 +1,11 @@ mod v1; mod v2; -pub use v1::ModifiedAtVersion; -pub use v1::ObjectReferenceWithOwner; -pub use v1::TransactionEffectsV1; -pub use v2::ChangedObject; -pub use v2::EffectsObjectChange; -pub use v2::IdOperation; -pub use v2::ObjectIn; -pub use v2::ObjectOut; -pub use v2::TransactionEffectsV2; -pub use v2::UnchangedSharedKind; -pub use v2::UnchangedSharedObject; +pub use v1::{ModifiedAtVersion, ObjectReferenceWithOwner, TransactionEffectsV1}; +pub use v2::{ + ChangedObject, EffectsObjectChange, IdOperation, ObjectIn, ObjectOut, TransactionEffectsV2, + UnchangedSharedKind, UnchangedSharedObject, +}; /// The response from processing a transaction or a certified transaction #[derive(Eq, PartialEq, Clone, Debug)] @@ -31,14 +25,9 @@ pub enum TransactionEffects { #[cfg(feature = "serde")] #[cfg_attr(doc_cfg, doc(cfg(feature = "serde")))] mod serialization { - use super::TransactionEffects; - use super::TransactionEffectsV1; - use super::TransactionEffectsV2; + use serde::{Deserialize, Deserializer, Serialize, Serializer}; - use serde::Deserialize; - use serde::Deserializer; - use serde::Serialize; - use serde::Serializer; + use super::{TransactionEffects, TransactionEffectsV1, TransactionEffectsV2}; #[derive(serde_derive::Serialize)] #[serde(tag = "version")] @@ -112,14 +101,12 @@ mod serialization { #[cfg(test)] mod tests { - use super::TransactionEffects; - - use base64ct::Base64; - use base64ct::Encoding; - + use base64ct::{Base64, Encoding}; #[cfg(target_arch = "wasm32")] use wasm_bindgen_test::wasm_bindgen_test as test; + use super::TransactionEffects; + #[test] fn effects_fixtures() { const GENESIS_EFFECTS: &str = include_str!("fixtures/genesis-transaction-effects"); diff --git a/crates/sui-sdk/src/types/effects/v1.rs b/crates/iota-rust-sdk/src/types/effects/v1.rs similarity index 93% rename from crates/sui-sdk/src/types/effects/v1.rs rename to crates/iota-rust-sdk/src/types/effects/v1.rs index aa04f3b..569ea82 100644 --- a/crates/sui-sdk/src/types/effects/v1.rs +++ b/crates/iota-rust-sdk/src/types/effects/v1.rs @@ -1,12 +1,8 @@ -use crate::types::execution_status::ExecutionStatus; -use crate::types::object::Owner; -use crate::types::object::Version; -use crate::types::EpochId; -use crate::types::GasCostSummary; -use crate::types::ObjectId; -use crate::types::ObjectReference; -use crate::types::TransactionDigest; -use crate::types::TransactionEventsDigest; +use crate::types::{ + execution_status::ExecutionStatus, + object::{Owner, Version}, + EpochId, GasCostSummary, ObjectId, ObjectReference, TransactionDigest, TransactionEventsDigest, +}; /// The response from processing a transaction or a certified transaction #[derive(Eq, PartialEq, Clone, Debug)] @@ -20,11 +16,12 @@ pub struct TransactionEffectsV1 { #[cfg_attr(feature = "schemars", schemars(with = "crate::_schemars::U64"))] epoch: EpochId, gas_used: GasCostSummary, - /// The version that every modified (mutated or deleted) object had before it was modified by - /// this transaction. + /// The version that every modified (mutated or deleted) object had before + /// it was modified by this transaction. #[cfg_attr(test, any(proptest::collection::size_range(0..=5).lift()))] modified_at_versions: Vec, - /// The object references of the shared objects used in this transaction. Empty if no shared objects were used. + /// The object references of the shared objects used in this transaction. + /// Empty if no shared objects were used. #[cfg_attr(test, any(proptest::collection::size_range(0..=5).lift()))] shared_objects: Vec, /// The transaction digest @@ -36,22 +33,23 @@ pub struct TransactionEffectsV1 { /// ObjectReference and owner of mutated objects, including gas object. #[cfg_attr(test, any(proptest::collection::size_range(0..=5).lift()))] mutated: Vec, - /// ObjectReference and owner of objects that are unwrapped in this transaction. - /// Unwrapped objects are objects that were wrapped into other objects in the past, - /// and just got extracted out. + /// ObjectReference and owner of objects that are unwrapped in this + /// transaction. Unwrapped objects are objects that were wrapped into + /// other objects in the past, and just got extracted out. #[cfg_attr(test, any(proptest::collection::size_range(0..=5).lift()))] unwrapped: Vec, /// Object Refs of objects now deleted (the new refs). #[cfg_attr(test, any(proptest::collection::size_range(0..=5).lift()))] deleted: Vec, - /// Object refs of objects previously wrapped in other objects but now deleted. + /// Object refs of objects previously wrapped in other objects but now + /// deleted. #[cfg_attr(test, any(proptest::collection::size_range(0..=5).lift()))] unwrapped_then_deleted: Vec, /// Object refs of objects now wrapped in other objects. #[cfg_attr(test, any(proptest::collection::size_range(0..=5).lift()))] wrapped: Vec, - /// The updated gas object reference. Have a dedicated field for convenient access. - /// It's also included in mutated. + /// The updated gas object reference. Have a dedicated field for convenient + /// access. It's also included in mutated. gas_object: ObjectReferenceWithOwner, /// The digest of the events emitted during execution, /// can be None if the transaction does not emit any event. @@ -90,10 +88,7 @@ pub struct ObjectReferenceWithOwner { #[cfg(feature = "serde")] #[cfg_attr(doc_cfg, doc(cfg(feature = "serde")))] mod serialization { - use serde::Deserialize; - use serde::Deserializer; - use serde::Serialize; - use serde::Serializer; + use serde::{Deserialize, Deserializer, Serialize, Serializer}; use super::*; diff --git a/crates/sui-sdk/src/types/effects/v2.rs b/crates/iota-rust-sdk/src/types/effects/v2.rs similarity index 95% rename from crates/sui-sdk/src/types/effects/v2.rs rename to crates/iota-rust-sdk/src/types/effects/v2.rs index 9b84881..2e4faa6 100644 --- a/crates/sui-sdk/src/types/effects/v2.rs +++ b/crates/iota-rust-sdk/src/types/effects/v2.rs @@ -1,13 +1,9 @@ -use crate::types::digest::EffectsAuxiliaryDataDigest; -use crate::types::execution_status::ExecutionStatus; -use crate::types::object::Owner; -use crate::types::object::Version; -use crate::types::EpochId; -use crate::types::GasCostSummary; -use crate::types::ObjectDigest; -use crate::types::ObjectId; -use crate::types::TransactionDigest; -use crate::types::TransactionEventsDigest; +use crate::types::{ + digest::EffectsAuxiliaryDataDigest, + execution_status::ExecutionStatus, + object::{Owner, Version}, + EpochId, GasCostSummary, ObjectDigest, ObjectId, TransactionDigest, TransactionEventsDigest, +}; /// The response from processing a transaction or a certified transaction #[derive(Eq, PartialEq, Clone, Debug)] @@ -23,8 +19,8 @@ pub struct TransactionEffectsV2 { pub gas_used: GasCostSummary, /// The transaction digest pub transaction_digest: TransactionDigest, - /// The updated gas object reference, as an index into the `changed_objects` vector. - /// Having a dedicated field for convenient access. + /// The updated gas object reference, as an index into the `changed_objects` + /// vector. Having a dedicated field for convenient access. /// System transaction that don't require gas will leave this as None. pub gas_object_index: Option, /// The digest of the events emitted during execution, @@ -40,19 +36,21 @@ pub struct TransactionEffectsV2 { /// Objects whose state are changed in the object store. #[cfg_attr(test, any(proptest::collection::size_range(0..=2).lift()))] pub changed_objects: Vec, - /// Shared objects that are not mutated in this transaction. Unlike owned objects, - /// read-only shared objects' version are not committed in the transaction, - /// and in order for a node to catch up and execute it without consensus sequencing, - /// the version needs to be committed in the effects. + /// Shared objects that are not mutated in this transaction. Unlike owned + /// objects, read-only shared objects' version are not committed in the + /// transaction, and in order for a node to catch up and execute it + /// without consensus sequencing, the version needs to be committed in + /// the effects. #[cfg_attr(test, any(proptest::collection::size_range(0..=2).lift()))] pub unchanged_shared_objects: Vec, - /// Auxiliary data that are not protocol-critical, generated as part of the effects but are stored separately. - /// Storing it separately allows us to avoid bloating the effects with data that are not critical. + /// Auxiliary data that are not protocol-critical, generated as part of the + /// effects but are stored separately. Storing it separately allows us + /// to avoid bloating the effects with data that are not critical. /// It also provides more flexibility on the format and type of the data. pub auxiliary_data_digest: Option, } -//XXX Do we maybe want to just fold "EffectsObjectChange" into this struct? +// XXX Do we maybe want to just fold "EffectsObjectChange" into this struct? #[derive(Eq, PartialEq, Clone, Debug)] #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] #[cfg_attr(test, derive(test_strategy::Arbitrary))] @@ -82,8 +80,9 @@ pub struct UnchangedSharedObject { )] #[cfg_attr(test, derive(test_strategy::Arbitrary))] pub enum UnchangedSharedKind { - /// Read-only shared objects from the input. We don't really need ObjectDigest - /// for protocol correctness, but it will make it easier to verify untrusted read. + /// Read-only shared objects from the input. We don't really need + /// ObjectDigest for protocol correctness, but it will make it easier to + /// verify untrusted read. ReadOnlyRoot { #[cfg_attr(feature = "schemars", schemars(with = "crate::_schemars::U64"))] version: Version, @@ -99,12 +98,14 @@ pub enum UnchangedSharedKind { #[cfg_attr(feature = "schemars", schemars(with = "crate::_schemars::U64"))] version: Version, }, - /// Shared objects in cancelled transaction. The sequence number embed cancellation reason. + /// Shared objects in cancelled transaction. The sequence number embed + /// cancellation reason. Cancelled { #[cfg_attr(feature = "schemars", schemars(with = "crate::_schemars::U64"))] version: Version, }, - /// Read of a per-epoch config object that should remain the same during an epoch. + /// Read of a per-epoch config object that should remain the same during an + /// epoch. PerEpochConfig, } @@ -124,8 +125,8 @@ pub struct EffectsObjectChange { pub output_state: ObjectOut, /// Whether this object ID is created or deleted in this transaction. - /// This information isn't required by the protocol but is useful for providing more detailed - /// semantics on object changes. + /// This information isn't required by the protocol but is useful for + /// providing more detailed semantics on object changes. pub id_operation: IdOperation, } @@ -188,10 +189,7 @@ pub enum IdOperation { #[cfg(feature = "serde")] #[cfg_attr(doc_cfg, doc(cfg(feature = "serde")))] mod serialization { - use serde::Deserialize; - use serde::Deserializer; - use serde::Serialize; - use serde::Serializer; + use serde::{Deserialize, Deserializer, Serialize, Serializer}; use super::*; diff --git a/crates/sui-sdk/src/types/events.rs b/crates/iota-rust-sdk/src/types/events.rs similarity index 92% rename from crates/sui-sdk/src/types/events.rs rename to crates/iota-rust-sdk/src/types/events.rs index cd46f58..601c75c 100644 --- a/crates/sui-sdk/src/types/events.rs +++ b/crates/iota-rust-sdk/src/types/events.rs @@ -1,8 +1,4 @@ -use super::Address; -use super::Identifier; -use super::ObjectId; -use super::StructTag; -use super::TypeTag; +use super::{Address, Identifier, ObjectId, StructTag, TypeTag}; #[derive(Eq, PartialEq, Clone, Debug)] #[cfg_attr( @@ -49,7 +45,8 @@ pub struct BalanceChange { pub coin_type: TypeTag, /// The amount indicate the balance value changes. /// - /// A negative amount means spending coin value and positive means receiving coin value. + /// A negative amount means spending coin value and positive means receiving + /// coin value. #[cfg_attr(feature = "serde", serde(with = "crate::_serde::ReadableDisplay"))] #[cfg_attr(feature = "schemars", schemars(with = "crate::_schemars::I128"))] pub amount: i128, diff --git a/crates/sui-sdk/src/types/execution_status.rs b/crates/iota-rust-sdk/src/types/execution_status.rs similarity index 96% rename from crates/sui-sdk/src/types/execution_status.rs rename to crates/iota-rust-sdk/src/types/execution_status.rs index ebf5686..bf07616 100644 --- a/crates/sui-sdk/src/types/execution_status.rs +++ b/crates/iota-rust-sdk/src/types/execution_status.rs @@ -1,7 +1,4 @@ -use super::Address; -use super::Digest; -use super::Identifier; -use super::ObjectId; +use super::{Address, Digest, Identifier, ObjectId}; #[derive(Eq, PartialEq, Clone, Debug)] #[cfg_attr(test, derive(test_strategy::Arbitrary))] @@ -17,8 +14,9 @@ pub enum ExecutionStatus { }, } -/// Type parameters are encoded as indices. This index can also be used to lookup the kind of a -/// type parameter in the `FunctionHandle` and `StructHandle`. +/// Type parameters are encoded as indices. This index can also be used to +/// lookup the kind of a type parameter in the `FunctionHandle` and +/// `StructHandle`. pub type TypeParameterIndex = u16; #[derive(Eq, PartialEq, Clone, Debug)] @@ -29,9 +27,7 @@ pub type TypeParameterIndex = u16; )] #[cfg_attr(test, derive(test_strategy::Arbitrary))] pub enum ExecutionError { - // // General transaction errors - // /// Insufficient Gas InsufficientGas, /// Invalid Gas Object. @@ -57,27 +53,21 @@ pub enum ExecutionError { /// Circular Object Ownership CircularObjectOwnership { object: ObjectId }, - // // Coin errors - // /// Insufficient coin balance for requested operation InsufficientCoinBalance, /// Coin balance overflowed an u64 CoinBalanceOverflow, - // // Publish/Upgrade errors - // /// Publish Error, Non-zero Address. /// The modules in the package must have their self-addresses set to zero. PublishErrorNonZeroAddress, - /// Sui Move Bytecode Verification Error. - SuiMoveVerificationError, + /// Iota Move Bytecode Verification Error. + IotaMoveVerificationError, - // // MoveVm Errors - // /// Error from a non-abort instruction. /// Possible causes: /// Arithmetic error, stack overflow, max value depth, etc." @@ -93,9 +83,7 @@ pub enum ExecutionError { /// MoveVm invariant violation VmInvariantViolation, - // // Programmable Transaction Errors - // /// Function not found FunctionNotFound, /// Arity mismatch for Move function. @@ -124,9 +112,7 @@ pub enum ExecutionError { /// Invalid Transfer Object, object does not have public transfer. InvalidTransferObject, - // // Post-execution errors - // /// Effects from the transaction are too large EffectsTooLarge { #[cfg_attr(feature = "schemars", schemars(with = "crate::_schemars::U64"))] @@ -140,9 +126,9 @@ pub enum ExecutionError { /// Publish or Upgrade dependency downgrade. /// - /// Indirect (transitive) dependency of published or upgraded package has been assigned an - /// on-chain version that is less than the version required by one of the package's - /// transitive dependencies. + /// Indirect (transitive) dependency of published or upgraded package has + /// been assigned an on-chain version that is less than the version + /// required by one of the package's transitive dependencies. PublishUpgradeDependencyDowngrade, /// Invalid package upgrade @@ -160,8 +146,8 @@ pub enum ExecutionError { /// Certificate is on the deny list CertificateDenied, - /// Sui Move Bytecode verification timed out. - SuiMoveVerificationTimedout, + /// Iota Move Bytecode verification timed out. + IotaMoveVerificationTimedout, /// The requested shared object operation is not allowed SharedObjectOperationNotAllowed, @@ -178,7 +164,8 @@ pub enum ExecutionError { /// Coin type is globally paused for use CoinTypeGlobalPause { coin_type: String }, - /// Certificate is cancelled because randomness could not be generated this epoch + /// Certificate is cancelled because randomness could not be generated this + /// epoch ExecutionCancelledDueToRandomnessUnavailable, } @@ -193,8 +180,8 @@ pub struct MoveLocation { pub package: ObjectId, pub module: Identifier, pub function: u16, - /// Index into the code stream for a jump. The offset is relative to the beginning of - /// the instruction stream. + /// Index into the code stream for a jump. The offset is relative to the + /// beginning of the instruction stream. pub instruction: u16, pub function_name: Option, } @@ -235,8 +222,8 @@ pub enum CommandArgumentError { InvalidObjectByValue, /// Immutable objects cannot be passed by mutable reference, &mut. InvalidObjectByMutRef, - /// Shared object operations such a wrapping, freezing, or converting to owned are not - /// allowed. + /// Shared object operations such a wrapping, freezing, or converting to + /// owned are not allowed. SharedObjectOperationNotAllowed, } @@ -287,12 +274,9 @@ pub enum TypeArgumentError { #[cfg(feature = "serde")] #[cfg_attr(doc_cfg, doc(cfg(feature = "serde")))] mod serialization { - use super::*; + use serde::{Deserialize, Deserializer, Serialize, Serializer}; - use serde::Deserialize; - use serde::Deserializer; - use serde::Serialize; - use serde::Serializer; + use super::*; #[derive(serde_derive::Serialize, serde_derive::Deserialize)] #[serde(rename = "ExecutionStatus")] @@ -420,7 +404,7 @@ mod serialization { InsufficientCoinBalance, CoinBalanceOverflow, PublishErrorNonZeroAddress, - SuiMoveVerificationError, + IotaMoveVerificationError, MovePrimitiveRuntimeError { location: Option, }, @@ -469,7 +453,7 @@ mod serialization { max_object_size: u64, }, CertificateDenied, - SuiMoveVerificationTimedout, + IotaMoveVerificationTimedout, SharedObjectOperationNotAllowed, InputObjectDeleted, ExecutionCancelledDueToSharedObjectCongestion { @@ -508,7 +492,7 @@ mod serialization { InsufficientCoinBalance, CoinBalanceOverflow, PublishErrorNonZeroAddress, - SuiMoveVerificationError, + IotaMoveVerificationError, MovePrimitiveRuntimeError { location: Option, }, @@ -552,7 +536,7 @@ mod serialization { max_object_size: u64, }, CertificateDenied, - SuiMoveVerificationTimedout, + IotaMoveVerificationTimedout, SharedObjectOperationNotAllowed, InputObjectDeleted, ExecutionCancelledDueToSharedObjectCongestion { @@ -606,8 +590,8 @@ mod serialization { Self::PublishErrorNonZeroAddress => { ReadableExecutionError::PublishErrorNonZeroAddress } - Self::SuiMoveVerificationError => { - ReadableExecutionError::SuiMoveVerificationError + Self::IotaMoveVerificationError => { + ReadableExecutionError::IotaMoveVerificationError } Self::MovePrimitiveRuntimeError { location } => { ReadableExecutionError::MovePrimitiveRuntimeError { location } @@ -666,8 +650,8 @@ mod serialization { max_object_size, }, Self::CertificateDenied => ReadableExecutionError::CertificateDenied, - Self::SuiMoveVerificationTimedout => { - ReadableExecutionError::SuiMoveVerificationTimedout + Self::IotaMoveVerificationTimedout => { + ReadableExecutionError::IotaMoveVerificationTimedout } Self::SharedObjectOperationNotAllowed => { ReadableExecutionError::SharedObjectOperationNotAllowed @@ -717,8 +701,8 @@ mod serialization { Self::PublishErrorNonZeroAddress => { BinaryExecutionError::PublishErrorNonZeroAddress } - Self::SuiMoveVerificationError => { - BinaryExecutionError::SuiMoveVerificationError + Self::IotaMoveVerificationError => { + BinaryExecutionError::IotaMoveVerificationError } Self::MovePrimitiveRuntimeError { location } => { BinaryExecutionError::MovePrimitiveRuntimeError { location } @@ -775,8 +759,8 @@ mod serialization { max_object_size, }, Self::CertificateDenied => BinaryExecutionError::CertificateDenied, - Self::SuiMoveVerificationTimedout => { - BinaryExecutionError::SuiMoveVerificationTimedout + Self::IotaMoveVerificationTimedout => { + BinaryExecutionError::IotaMoveVerificationTimedout } Self::SharedObjectOperationNotAllowed => { BinaryExecutionError::SharedObjectOperationNotAllowed @@ -837,8 +821,8 @@ mod serialization { ReadableExecutionError::PublishErrorNonZeroAddress => { Self::PublishErrorNonZeroAddress } - ReadableExecutionError::SuiMoveVerificationError => { - Self::SuiMoveVerificationError + ReadableExecutionError::IotaMoveVerificationError => { + Self::IotaMoveVerificationError } ReadableExecutionError::MovePrimitiveRuntimeError { location } => { Self::MovePrimitiveRuntimeError { location } @@ -897,8 +881,8 @@ mod serialization { max_object_size, }, ReadableExecutionError::CertificateDenied => Self::CertificateDenied, - ReadableExecutionError::SuiMoveVerificationTimedout => { - Self::SuiMoveVerificationTimedout + ReadableExecutionError::IotaMoveVerificationTimedout => { + Self::IotaMoveVerificationTimedout } ReadableExecutionError::SharedObjectOperationNotAllowed => { Self::SharedObjectOperationNotAllowed @@ -945,8 +929,8 @@ mod serialization { BinaryExecutionError::PublishErrorNonZeroAddress => { Self::PublishErrorNonZeroAddress } - BinaryExecutionError::SuiMoveVerificationError => { - Self::SuiMoveVerificationError + BinaryExecutionError::IotaMoveVerificationError => { + Self::IotaMoveVerificationError } BinaryExecutionError::MovePrimitiveRuntimeError { location } => { Self::MovePrimitiveRuntimeError { location } @@ -1003,8 +987,8 @@ mod serialization { max_object_size, }, BinaryExecutionError::CertificateDenied => Self::CertificateDenied, - BinaryExecutionError::SuiMoveVerificationTimedout => { - Self::SuiMoveVerificationTimedout + BinaryExecutionError::IotaMoveVerificationTimedout => { + Self::IotaMoveVerificationTimedout } BinaryExecutionError::SharedObjectOperationNotAllowed => { Self::SharedObjectOperationNotAllowed diff --git a/crates/sui-sdk/src/types/framework.rs b/crates/iota-rust-sdk/src/types/framework.rs similarity index 91% rename from crates/sui-sdk/src/types/framework.rs rename to crates/iota-rust-sdk/src/types/framework.rs index 38c7ebb..0e9fc4d 100644 --- a/crates/sui-sdk/src/types/framework.rs +++ b/crates/iota-rust-sdk/src/types/framework.rs @@ -1,8 +1,6 @@ -//! Rust definitions of move/sui framework types. +//! Rust definitions of move/iota framework types. -use super::Object; -use super::ObjectId; -use super::TypeTag; +use super::{Object, ObjectId, TypeTag}; #[derive(Debug, Clone)] pub struct Coin<'a> { diff --git a/crates/sui-sdk/src/types/gas.rs b/crates/iota-rust-sdk/src/types/gas.rs similarity index 77% rename from crates/sui-sdk/src/types/gas.rs rename to crates/iota-rust-sdk/src/types/gas.rs index 45417f1..afba1fc 100644 --- a/crates/sui-sdk/src/types/gas.rs +++ b/crates/iota-rust-sdk/src/types/gas.rs @@ -2,24 +2,25 @@ /// /// Storage is charged independently of computation. /// There are 3 parts to the storage charges: -/// `storage_cost`: it is the charge of storage at the time the transaction is executed. -/// The cost of storage is the number of bytes of the objects being mutated -/// multiplied by a variable storage cost per byte -/// `storage_rebate`: this is the amount a user gets back when manipulating an object. -/// The `storage_rebate` is the `storage_cost` for an object minus fees. -/// `non_refundable_storage_fee`: not all the value of the object storage cost is -/// given back to user and there is a small fraction that -/// is kept by the system. This value tracks that charge. +/// `storage_cost`: it is the charge of storage at the time the transaction is +/// executed. The cost of storage is the number of bytes of the +/// objects being mutated multiplied by a variable storage cost +/// per byte `storage_rebate`: this is the amount a user gets back when +/// manipulating an object. The `storage_rebate` is the +/// `storage_cost` for an object minus fees. `non_refundable_storage_fee`: not +/// all the value of the object storage cost is +/// given back to user and there is a small fraction that +/// is kept by the system. This value tracks that charge. /// /// When looking at a gas cost summary the amount charged to the user is /// `computation_cost + storage_cost - storage_rebate` /// and that is the amount that is deducted from the gas coins. -/// `non_refundable_storage_fee` is collected from the objects being mutated/deleted -/// and it is tracked by the system in storage funds. +/// `non_refundable_storage_fee` is collected from the objects being +/// mutated/deleted and it is tracked by the system in storage funds. /// -/// Objects deleted, including the older versions of objects mutated, have the storage field -/// on the objects added up to a pool of "potential rebate". This rebate then is reduced -/// by the "nonrefundable rate" such that: +/// Objects deleted, including the older versions of objects mutated, have the +/// storage field on the objects added up to a pool of "potential rebate". This +/// rebate then is reduced by the "nonrefundable rate" such that: /// `potential_rebate(storage cost of deleted/mutated objects) = /// storage_rebate + non_refundable_storage_fee` #[derive(Clone, Debug, Default, PartialEq, Eq)] @@ -35,18 +36,20 @@ pub struct GasCostSummary { #[cfg_attr(feature = "schemars", schemars(with = "crate::_schemars::U64"))] pub computation_cost: u64, - /// Storage cost, it's the sum of all storage cost for all objects created or mutated. + /// Storage cost, it's the sum of all storage cost for all objects created + /// or mutated. #[cfg_attr(feature = "serde", serde(with = "crate::_serde::ReadableDisplay"))] #[cfg_attr(feature = "schemars", schemars(with = "crate::_schemars::U64"))] pub storage_cost: u64, - /// The amount of storage cost refunded to the user for all objects deleted or mutated in the - /// transaction. + /// The amount of storage cost refunded to the user for all objects deleted + /// or mutated in the transaction. #[cfg_attr(feature = "serde", serde(with = "crate::_serde::ReadableDisplay"))] #[cfg_attr(feature = "schemars", schemars(with = "crate::_schemars::U64"))] pub storage_rebate: u64, - /// The fee for the rebate. The portion of the storage rebate kept by the system. + /// The fee for the rebate. The portion of the storage rebate kept by the + /// system. #[cfg_attr(feature = "serde", serde(with = "crate::_serde::ReadableDisplay"))] #[cfg_attr(feature = "schemars", schemars(with = "crate::_schemars::U64"))] pub non_refundable_storage_fee: u64, @@ -71,7 +74,8 @@ impl GasCostSummary { self.computation_cost + self.storage_cost } - /// Get net gas usage, positive number means used gas; negative number means refund. + /// Get net gas usage, positive number means used gas; negative number means + /// refund. pub fn net_gas_usage(&self) -> i64 { self.gas_used() as i64 - self.storage_rebate as i64 } @@ -92,11 +96,11 @@ impl std::fmt::Display for GasCostSummary { #[cfg(test)] mod test { - use super::*; - #[cfg(target_arch = "wasm32")] use wasm_bindgen_test::wasm_bindgen_test as test; + use super::*; + #[test] #[cfg(feature = "serde")] fn formats() { diff --git a/crates/iota-rust-sdk/src/types/mod.rs b/crates/iota-rust-sdk/src/types/mod.rs new file mode 100644 index 0000000..2d97d8c --- /dev/null +++ b/crates/iota-rust-sdk/src/types/mod.rs @@ -0,0 +1,69 @@ +mod address; +mod checkpoint; +mod crypto; +mod digest; +mod effects; +mod events; +mod execution_status; +pub mod framework; +mod gas; +mod object; +mod object_id; +mod transaction; +mod type_tag; +mod u256; + +pub use address::Address; +pub use checkpoint::{ + CheckpointCommitment, CheckpointContents, CheckpointData, CheckpointSequenceNumber, + CheckpointSummary, CheckpointTimestamp, CheckpointTransaction, CheckpointTransactionInfo, + EndOfEpochData, EpochId, ProtocolVersion, SignedCheckpointSummary, StakeUnit, +}; +pub use crypto::{ + Bls12381PrivateKey, Bls12381PublicKey, Bls12381Signature, Bn254FieldElement, CircomG1, + CircomG2, Claim, Ed25519PrivateKey, Ed25519PublicKey, Ed25519Signature, Jwk, JwkId, JwtDetails, + MultisigAggregatedSignature, MultisigCommittee, MultisigMember, MultisigMemberPublicKey, + MultisigMemberSignature, PasskeyAuthenticator, PasskeyPublicKey, Secp256k1PrivateKey, + Secp256k1PublicKey, Secp256k1Signature, Secp256r1PrivateKey, Secp256r1PublicKey, + Secp256r1Signature, SignatureScheme, SimpleSignature, UserSignature, + ValidatorAggregatedSignature, ValidatorCommittee, ValidatorCommitteeMember, ValidatorSignature, + ZkLoginAuthenticator, ZkLoginInputs, ZkLoginProof, ZkLoginPublicIdentifier, +}; +pub use digest::{ + CheckpointContentsDigest, CheckpointDigest, ConsensusCommitDigest, Digest, DigestParseError, + EffectsAuxiliaryDataDigest, ObjectDigest, TransactionDigest, TransactionEffectsDigest, + TransactionEventsDigest, +}; +pub use effects::{ + ChangedObject, EffectsObjectChange, IdOperation, ModifiedAtVersion, ObjectIn, ObjectOut, + ObjectReferenceWithOwner, TransactionEffects, TransactionEffectsV1, TransactionEffectsV2, + UnchangedSharedKind, UnchangedSharedObject, +}; +pub use events::{BalanceChange, Event, TransactionEvents}; +pub use execution_status::{ + CommandArgumentError, ExecutionError, ExecutionStatus, MoveLocation, PackageUpgradeError, + TypeArgumentError, +}; +pub use gas::GasCostSummary; +pub use object::{ + GenesisObject, Object, ObjectData, ObjectReference, ObjectType, Owner, TypeOrigin, UpgradeInfo, + Version, +}; +pub use object_id::ObjectId; +#[cfg(feature = "serde")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "serde")))] +pub(crate) use transaction::SignedTransactionWithIntentMessage; +pub use transaction::{ + ActiveJwk, Argument, AuthenticatorStateExpire, AuthenticatorStateUpdate, CancelledTransaction, + ChangeEpoch, Command, ConsensusCommitPrologue, ConsensusCommitPrologueV2, + ConsensusCommitPrologueV3, ConsensusDeterminedVersionAssignments, EndOfEpochTransactionKind, + GasPayment, GenesisTransaction, InputArgument, MakeMoveVector, MergeCoins, MoveCall, + ProgrammableTransaction, Publish, RandomnessStateUpdate, SignedTransaction, SplitCoins, + SystemPackage, Transaction, TransactionExpiration, TransactionKind, TransferObjects, + UnresolvedGasPayment, UnresolvedInputArgument, UnresolvedObjectReference, + UnresolvedProgrammableTransaction, UnresolvedTransaction, Upgrade, VersionAssignment, +}; +pub use type_tag::{Identifier, StructTag, TypeParseError, TypeTag}; + +#[cfg(test)] +mod serialization_proptests; diff --git a/crates/sui-sdk/src/types/object.rs b/crates/iota-rust-sdk/src/types/object.rs similarity index 93% rename from crates/sui-sdk/src/types/object.rs rename to crates/iota-rust-sdk/src/types/object.rs index f8f86e6..b92c872 100644 --- a/crates/sui-sdk/src/types/object.rs +++ b/crates/iota-rust-sdk/src/types/object.rs @@ -1,11 +1,6 @@ use std::collections::BTreeMap; -use super::Address; -use super::Identifier; -use super::ObjectDigest; -use super::ObjectId; -use super::StructTag; -use super::TransactionDigest; +use super::{Address, Identifier, ObjectDigest, ObjectId, StructTag, TransactionDigest}; pub type Version = u64; @@ -91,17 +86,17 @@ pub enum Owner { )] #[allow(clippy::large_enum_variant)] #[cfg_attr(test, derive(test_strategy::Arbitrary))] -//TODO think about hiding this type and not exposing it +// TODO think about hiding this type and not exposing it pub enum ObjectData { /// An object whose governing logic lives in a published Move module Struct(MoveStruct), /// Map from each module name to raw serialized Move module bytes Package(MovePackage), - // ... Sui "native" types go here + // ... Iota "native" types go here } -// serde_bytes::ByteBuf is an analog of Vec with built-in fast serialization. -// #[serde_as] +// serde_bytes::ByteBuf is an analog of Vec with built-in fast +// serialization. #[serde_as] #[derive(Eq, PartialEq, Debug, Clone, Hash)] #[cfg_attr( feature = "serde", @@ -110,16 +105,17 @@ pub enum ObjectData { #[cfg_attr(test, derive(test_strategy::Arbitrary))] pub struct MovePackage { id: ObjectId, - /// Most move packages are uniquely identified by their ID (i.e. there is only one version per - /// ID), but the version is still stored because one package may be an upgrade of another (at a - /// different ID), in which case its version will be one greater than the version of the + /// Most move packages are uniquely identified by their ID (i.e. there is + /// only one version per ID), but the version is still stored because + /// one package may be an upgrade of another (at a different ID), in + /// which case its version will be one greater than the version of the /// upgraded package. /// - /// Framework packages are an exception to this rule -- all versions of the framework packages - /// exist at the same ID, at increasing versions. + /// Framework packages are an exception to this rule -- all versions of the + /// framework packages exist at the same ID, at increasing versions. /// - /// In all cases, packages are referred to by move calls using just their ID, and they are - /// always loaded at their latest version. + /// In all cases, packages are referred to by move calls using just their + /// ID, and they are always loaded at their latest version. #[cfg_attr(feature = "serde", serde(with = "crate::_serde::ReadableDisplay"))] version: Version, @@ -135,8 +131,8 @@ pub struct MovePackage { )] modules: BTreeMap>, - /// Maps struct/module to a package version where it was first defined, stored as a vector for - /// simple serialization and deserialization. + /// Maps struct/module to a package version where it was first defined, + /// stored as a vector for simple serialization and deserialization. type_origin_table: Vec, // For each dependency, maps original package ID to the info about the (upgraded) dependency @@ -194,11 +190,13 @@ pub struct MoveStruct { serde(with = "::serde_with::As::") )] pub(crate) type_: StructTag, - /// DEPRECATED this field is no longer used to determine whether a tx can transfer this - /// object. Instead, it is always calculated from the objects type when loaded in execution + /// DEPRECATED this field is no longer used to determine whether a tx can + /// transfer this object. Instead, it is always calculated from the + /// objects type when loaded in execution has_public_transfer: bool, - /// Number that increases each time a tx takes this object as a mutable input - /// This is a lamport timestamp, not a sequentially increasing version + /// Number that increases each time a tx takes this object as a mutable + /// input This is a lamport timestamp, not a sequentially increasing + /// version #[cfg_attr(feature = "serde", serde(with = "crate::_serde::ReadableDisplay"))] version: Version, /// BCS bytes of a Move struct value @@ -210,7 +208,7 @@ pub struct MoveStruct { pub(crate) contents: Vec, } -/// Type of a Sui object +/// Type of a Iota object #[derive(Clone, Ord, PartialOrd, Eq, PartialEq, Debug)] pub enum ObjectType { /// Move package containing one or more bytecode modules @@ -228,7 +226,7 @@ pub struct Object { owner: Owner, /// The digest of the transaction that created or last mutated this object previous_transaction: TransactionDigest, - /// The amount of SUI we would rebate if this object gets deleted. + /// The amount of IOTA we would rebate if this object gets deleted. /// This number is re-calculated each time the object is mutated based on /// the present storage gas price. storage_rebate: u64, @@ -301,19 +299,14 @@ impl GenesisObject { } } -//TODO improve ser/de to do borrowing to avoid clones where possible +// TODO improve ser/de to do borrowing to avoid clones where possible #[cfg(feature = "serde")] #[cfg_attr(doc_cfg, doc(cfg(feature = "serde")))] mod serialization { - use std::borrow::Cow; - use std::str::FromStr; + use std::{borrow::Cow, str::FromStr}; - use serde::Deserialize; - use serde::Deserializer; - use serde::Serialize; - use serde::Serializer; - use serde_with::DeserializeAs; - use serde_with::SerializeAs; + use serde::{Deserialize, Deserializer, Serialize, Serializer}; + use serde_with::{DeserializeAs, SerializeAs}; use super::*; use crate::types::TypeTag; @@ -354,19 +347,23 @@ mod serialization { ); } - /// Wrapper around StructTag with a space-efficient representation for common types like coins - /// The StructTag for a gas coin is 84 bytes, so using 1 byte instead is a win. - /// The inner representation is private to prevent incorrectly constructing an `Other` instead of - /// one of the specialized variants, e.g. `Other(GasCoin::type_())` instead of `GasCoin` + /// Wrapper around StructTag with a space-efficient representation for + /// common types like coins The StructTag for a gas coin is 84 bytes, so + /// using 1 byte instead is a win. The inner representation is private + /// to prevent incorrectly constructing an `Other` instead of one of the + /// specialized variants, e.g. `Other(GasCoin::type_())` instead of + /// `GasCoin` #[derive(serde_derive::Deserialize)] enum MoveStructType { /// A type that is not `0x2::coin::Coin` Other(StructTag), - /// A SUI coin (i.e., `0x2::coin::Coin<0x2::sui::SUI>`) + /// A IOTA coin (i.e., `0x2::coin::Coin<0x2::iota::IOTA>`) GasCoin, - /// A record of a staked SUI coin (i.e., `0x3::staking_pool::StakedSui`) - StakedSui, - /// A non-SUI coin type (i.e., `0x2::coin::Coin where T != 0x2::sui::SUI`) + /// A record of a staked IOTA coin (i.e., + /// `0x3::staking_pool::StakedIota`) + StakedIota, + /// A non-IOTA coin type (i.e., `0x2::coin::Coin where T != + /// 0x2::iota::IOTA`) Coin(TypeTag), // NOTE: if adding a new type here, and there are existing on-chain objects of that // type with Other(_), that is ok, but you must hand-roll PartialEq/Eq/Ord/maybe Hash @@ -378,11 +375,13 @@ mod serialization { enum MoveStructTypeRef<'a> { /// A type that is not `0x2::coin::Coin` Other(&'a StructTag), - /// A SUI coin (i.e., `0x2::coin::Coin<0x2::sui::SUI>`) + /// A IOTA coin (i.e., `0x2::coin::Coin<0x2::iota::IOTA>`) GasCoin, - /// A record of a staked SUI coin (i.e., `0x3::staking_pool::StakedSui`) - StakedSui, - /// A non-SUI coin type (i.e., `0x2::coin::Coin where T != 0x2::sui::SUI`) + /// A record of a staked IOTA coin (i.e., + /// `0x3::staking_pool::StakedIota`) + StakedIota, + /// A non-IOTA coin type (i.e., `0x2::coin::Coin where T != + /// 0x2::iota::IOTA`) Coin(&'a TypeTag), // NOTE: if adding a new type here, and there are existing on-chain objects of that // type with Other(_), that is ok, but you must hand-roll PartialEq/Eq/Ord/maybe Hash @@ -394,7 +393,7 @@ mod serialization { match self { MoveStructType::Other(tag) => tag, MoveStructType::GasCoin => StructTag::gas_coin(), - MoveStructType::StakedSui => StructTag::staked_sui(), + MoveStructType::StakedIota => StructTag::staked_iota(), MoveStructType::Coin(type_tag) => StructTag::coin(type_tag), } } @@ -419,8 +418,8 @@ mod serialization { } = s_inner.as_ref(); if address == &Address::TWO - && module == "sui" - && name == "SUI" + && module == "iota" + && name == "IOTA" && type_params.is_empty() { return Self::GasCoin; @@ -430,10 +429,10 @@ mod serialization { Self::Coin(coin_type) } else if address == &Address::THREE && module == "staking_pool" - && name == "StakedSui" + && name == "StakedIota" && type_params.is_empty() { - Self::StakedSui + Self::StakedIota } else { Self::Other(s) } @@ -841,14 +840,14 @@ mod serialization { #[cfg(test)] mod test { - use crate::types::object::Object; - #[cfg(target_arch = "wasm32")] use wasm_bindgen_test::wasm_bindgen_test as test; + use crate::types::object::Object; + #[test] fn object_fixture() { - const SUI_COIN: &[u8] = &[ + const IOTA_COIN: &[u8] = &[ 0, 1, 1, 32, 79, 43, 0, 0, 0, 0, 0, 40, 35, 95, 175, 213, 151, 87, 206, 190, 35, 131, 79, 35, 254, 22, 15, 181, 40, 108, 28, 77, 68, 229, 107, 254, 191, 160, 196, 186, 42, 2, 122, 53, 52, 133, 199, 58, 0, 0, 0, 0, 0, 79, 255, 208, 0, 85, 34, 190, @@ -858,7 +857,7 @@ mod serialization { 141, 20, 15, 85, 96, 19, 15, 0, 0, 0, 0, 0, ]; - const SUI_STAKE: &[u8] = &[ + const IOTA_STAKE: &[u8] = &[ 0, 2, 1, 154, 1, 52, 5, 0, 0, 0, 0, 80, 3, 112, 71, 231, 166, 234, 205, 164, 99, 237, 29, 56, 97, 170, 21, 96, 105, 158, 227, 122, 22, 251, 60, 162, 12, 97, 151, 218, 71, 253, 231, 239, 116, 138, 12, 233, 128, 195, 128, 77, 33, 38, 122, 77, 53, @@ -948,7 +947,7 @@ mod serialization { 13, 89, 18, 159, 205, 129, 112, 131, 112, 192, 126, 0, 0, 0, 0, 0, ]; - for fixture in [SUI_COIN, SUI_STAKE, NFT, FUD_COIN, BULLSHARK_PACKAGE] { + for fixture in [IOTA_COIN, IOTA_STAKE, NFT, FUD_COIN, BULLSHARK_PACKAGE] { let object: Object = bcs::from_bytes(fixture).unwrap(); assert_eq!(bcs::to_bytes(&object).unwrap(), fixture); diff --git a/crates/sui-sdk/src/types/object_id.rs b/crates/iota-rust-sdk/src/types/object_id.rs similarity index 100% rename from crates/sui-sdk/src/types/object_id.rs rename to crates/iota-rust-sdk/src/types/object_id.rs diff --git a/crates/sui-sdk/src/types/serialization_proptests.rs b/crates/iota-rust-sdk/src/types/serialization_proptests.rs similarity index 100% rename from crates/sui-sdk/src/types/serialization_proptests.rs rename to crates/iota-rust-sdk/src/types/serialization_proptests.rs index 0222ecf..31c6dec 100644 --- a/crates/sui-sdk/src/types/serialization_proptests.rs +++ b/crates/iota-rust-sdk/src/types/serialization_proptests.rs @@ -1,9 +1,9 @@ -use crate::types::*; use test_strategy::proptest; - #[cfg(target_arch = "wasm32")] use wasm_bindgen_test::wasm_bindgen_test as test; +use crate::types::*; + macro_rules! serialization_test { ($type:ident) => { paste::item! { diff --git a/crates/sui-sdk/src/types/transaction/fixtures/authenticator_state_update b/crates/iota-rust-sdk/src/types/transaction/fixtures/authenticator_state_update similarity index 100% rename from crates/sui-sdk/src/types/transaction/fixtures/authenticator_state_update rename to crates/iota-rust-sdk/src/types/transaction/fixtures/authenticator_state_update diff --git a/crates/sui-sdk/src/types/transaction/fixtures/genesis-transaction b/crates/iota-rust-sdk/src/types/transaction/fixtures/genesis-transaction similarity index 100% rename from crates/sui-sdk/src/types/transaction/fixtures/genesis-transaction rename to crates/iota-rust-sdk/src/types/transaction/fixtures/genesis-transaction diff --git a/crates/sui-sdk/src/types/transaction/fixtures/wormhole-pyth-transaction b/crates/iota-rust-sdk/src/types/transaction/fixtures/wormhole-pyth-transaction similarity index 100% rename from crates/sui-sdk/src/types/transaction/fixtures/wormhole-pyth-transaction rename to crates/iota-rust-sdk/src/types/transaction/fixtures/wormhole-pyth-transaction diff --git a/crates/sui-sdk/src/types/transaction/mod.rs b/crates/iota-rust-sdk/src/types/transaction/mod.rs similarity index 92% rename from crates/sui-sdk/src/types/transaction/mod.rs rename to crates/iota-rust-sdk/src/types/transaction/mod.rs index 7019578..ae88918 100644 --- a/crates/sui-sdk/src/types/transaction/mod.rs +++ b/crates/iota-rust-sdk/src/types/transaction/mod.rs @@ -1,18 +1,8 @@ -use super::Address; -use super::CheckpointTimestamp; -use super::ConsensusCommitDigest; -use super::EpochId; -use super::GenesisObject; -use super::Identifier; -use super::Jwk; -use super::JwkId; -use super::ObjectId; -use super::ObjectReference; -use super::ProtocolVersion; -use super::TransactionDigest; -use super::TypeTag; -use super::UserSignature; -use super::Version; +use super::{ + Address, CheckpointTimestamp, ConsensusCommitDigest, EpochId, GenesisObject, Identifier, Jwk, + JwkId, ObjectId, ObjectReference, ProtocolVersion, TransactionDigest, TypeTag, UserSignature, + Version, +}; #[cfg(feature = "serde")] #[cfg_attr(doc_cfg, doc(cfg(feature = "serde")))] @@ -22,11 +12,10 @@ mod serialization; pub(crate) use serialization::SignedTransactionWithIntentMessage; mod unresolved; -pub use unresolved::UnresolvedGasPayment; -pub use unresolved::UnresolvedInputArgument; -pub use unresolved::UnresolvedObjectReference; -pub use unresolved::UnresolvedProgrammableTransaction; -pub use unresolved::UnresolvedTransaction; +pub use unresolved::{ + UnresolvedGasPayment, UnresolvedInputArgument, UnresolvedObjectReference, + UnresolvedProgrammableTransaction, UnresolvedTransaction, +}; #[derive(Clone, Debug, PartialEq, Eq)] #[cfg_attr(test, derive(test_strategy::Arbitrary))] @@ -111,7 +100,8 @@ pub struct RandomnessStateUpdate { #[derive(Clone, Debug, PartialEq, Eq)] #[cfg_attr(test, derive(test_strategy::Arbitrary))] pub enum TransactionKind { - /// A transaction that allows the interleaving of native commands and Move calls + /// A transaction that allows the interleaving of native commands and Move + /// calls ProgrammableTransaction(ProgrammableTransaction), /// A system transaction that will update epoch information on-chain. /// It will only ever be executed once in an epoch. @@ -119,18 +109,18 @@ pub enum TransactionKind { /// because it ensures that this transaction has a unique digest. /// This will eventually be translated to a Move call during execution. /// It also doesn't require/use a gas object. - /// A validator will not sign a transaction of this kind from outside. It only - /// signs internally during epoch changes. + /// A validator will not sign a transaction of this kind from outside. It + /// only signs internally during epoch changes. /// - /// The ChangeEpoch enumerant is now deprecated (but the ChangeEpoch struct is still used by - /// EndOfEpochTransaction below). + /// The ChangeEpoch enumerant is now deprecated (but the ChangeEpoch struct + /// is still used by EndOfEpochTransaction below). ChangeEpoch(ChangeEpoch), Genesis(GenesisTransaction), ConsensusCommitPrologue(ConsensusCommitPrologue), AuthenticatorStateUpdate(AuthenticatorStateUpdate), - /// EndOfEpochTransaction replaces ChangeEpoch with a list of transactions that are allowed to - /// run at the end of the epoch. + /// EndOfEpochTransaction replaces ChangeEpoch with a list of transactions + /// that are allowed to run at the end of the epoch. EndOfEpoch(Vec), RandomnessStateUpdate(RandomnessStateUpdate), @@ -225,7 +215,8 @@ pub struct ActiveJwk { } /// Only commit_timestamp_ms is passed to the move call currently. -/// However we include epoch and round to make sure each ConsensusCommitPrologue has a unique tx digest. +/// However we include epoch and round to make sure each ConsensusCommitPrologue +/// has a unique tx digest. #[derive(Clone, Debug, PartialEq, Eq)] #[cfg_attr( feature = "serde", @@ -330,8 +321,8 @@ pub struct ConsensusCommitPrologueV3 { #[cfg_attr(feature = "serde", serde(with = "crate::_serde::ReadableDisplay"))] #[cfg_attr(feature = "schemars", schemars(with = "crate::_schemars::U64"))] pub round: u64, - /// The sub DAG index of the consensus commit. This field will be populated if there - /// are multiple consensus commits per round. + /// The sub DAG index of the consensus commit. This field will be populated + /// if there are multiple consensus commits per round. #[cfg_attr( feature = "serde", serde(with = "crate::_serde::OptionReadableDisplay") @@ -384,11 +375,12 @@ pub struct ChangeEpoch { #[cfg_attr(feature = "serde", serde(with = "crate::_serde::ReadableDisplay"))] #[cfg_attr(feature = "schemars", schemars(with = "crate::_schemars::U64"))] pub epoch_start_timestamp_ms: u64, - /// System packages (specifically framework and move stdlib) that are written before the new - /// epoch starts. This tracks framework upgrades on chain. When executing the ChangeEpoch txn, - /// the validator must write out the modules below. Modules are provided with the version they - /// will be upgraded to, their modules in serialized form (which include their package ID), and - /// a list of their transitive dependencies. + /// System packages (specifically framework and move stdlib) that are + /// written before the new epoch starts. This tracks framework upgrades + /// on chain. When executing the ChangeEpoch txn, the validator must + /// write out the modules below. Modules are provided with the version they + /// will be upgraded to, their modules in serialized form (which include + /// their package ID), and a list of their transitive dependencies. #[cfg_attr(test, any(proptest::collection::size_range(0..=2).lift()))] pub system_packages: Vec, } @@ -463,7 +455,8 @@ pub enum InputArgument { // A Move object, either immutable, or owned mutable. ImmutableOrOwned(ObjectReference), // A Move object that's shared. - // SharedObject::mutable controls whether caller asks for a mutable reference to shared object. + // SharedObject::mutable controls whether caller asks for a mutable reference to shared + // object. Shared { object_id: ObjectId, #[cfg_attr(feature = "schemars", schemars(with = "crate::_schemars::U64"))] @@ -486,9 +479,9 @@ pub enum Command { /// A call to either an entry or a public Move function MoveCall(MoveCall), /// `(Vec, address)` - /// It sends n-objects to the specified address. These objects must have store - /// (public transfer) and either the previous owner must be an address or the object must - /// be newly created. + /// It sends n-objects to the specified address. These objects must have + /// store (public transfer) and either the previous owner must be an + /// address or the object must be newly created. TransferObjects(TransferObjects), /// `(&mut Coin, Vec)` -> `Vec>` /// It splits off some amounts into a new coins with those amounts @@ -496,20 +489,21 @@ pub enum Command { /// `(&mut Coin, Vec>)` /// It merges n-coins into the first coin MergeCoins(MergeCoins), - /// Publishes a Move package. It takes the package bytes and a list of the package's transitive - /// dependencies to link against on-chain. + /// Publishes a Move package. It takes the package bytes and a list of the + /// package's transitive dependencies to link against on-chain. Publish(Publish), /// `forall T: Vec -> vector` - /// Given n-values of the same type, it constructs a vector. For non objects or an empty vector, - /// the type tag must be specified. + /// Given n-values of the same type, it constructs a vector. For non objects + /// or an empty vector, the type tag must be specified. MakeMoveVector(MakeMoveVector), /// Upgrades a Move package /// Takes (in order): /// 1. A vector of serialized modules for the package. - /// 2. A vector of object ids for the transitive dependencies of the new package. + /// 2. A vector of object ids for the transitive dependencies of the new + /// package. /// 3. The object ID of the package being upgraded. - /// 4. An argument holding the `UpgradeTicket` that must have been produced from an earlier command in the same - /// programmable transaction. + /// 4. An argument holding the `UpgradeTicket` that must have been produced + /// from an earlier command in the same programmable transaction. Upgrade(Upgrade), } @@ -618,14 +612,15 @@ pub enum Argument { Input(u16), /// The result of another command (from `ProgrammableTransaction` commands) Result(u16), - /// Like a `Result` but it accesses a nested result. Currently, the only usage - /// of this is to access a value from a Move call with multiple return values. + /// Like a `Result` but it accesses a nested result. Currently, the only + /// usage of this is to access a value from a Move call with multiple + /// return values. // (command index, subresult index) NestedResult(u16, u16), } -/// The command for calling a Move function, either an entry function or a public -/// function (which cannot return references). +/// The command for calling a Move function, either an entry function or a +/// public function (which cannot return references). #[derive(Clone, Debug, PartialEq, Eq)] #[cfg_attr( feature = "serde", diff --git a/crates/sui-sdk/src/types/transaction/serialization.rs b/crates/iota-rust-sdk/src/types/transaction/serialization.rs similarity index 95% rename from crates/sui-sdk/src/types/transaction/serialization.rs rename to crates/iota-rust-sdk/src/types/transaction/serialization.rs index 23102a9..95e7f0b 100644 --- a/crates/sui-sdk/src/types/transaction/serialization.rs +++ b/crates/iota-rust-sdk/src/types/transaction/serialization.rs @@ -1,22 +1,15 @@ -use serde::Deserialize; -use serde::Deserializer; -use serde::Serialize; -use serde::Serializer; -use serde_with::DeserializeAs; -use serde_with::SerializeAs; - -use crate::types::ObjectId; -use crate::types::ObjectReference; +use serde::{Deserialize, Deserializer, Serialize, Serializer}; +use serde_with::{DeserializeAs, SerializeAs}; use super::Argument; +use crate::types::{ObjectId, ObjectReference}; mod transaction { use super::*; - use crate::types::transaction::GasPayment; - use crate::types::transaction::Transaction; - use crate::types::transaction::TransactionExpiration; - use crate::types::transaction::TransactionKind; - use crate::types::Address; + use crate::types::{ + transaction::{GasPayment, Transaction, TransactionExpiration, TransactionKind}, + Address, + }; #[derive(serde_derive::Serialize)] #[serde(tag = "version")] @@ -130,16 +123,11 @@ mod transaction { mod transaction_kind { use super::*; - use crate::types::transaction::AuthenticatorStateUpdate; - use crate::types::transaction::ChangeEpoch; - use crate::types::transaction::ConsensusCommitPrologue; - use crate::types::transaction::ConsensusCommitPrologueV2; - use crate::types::transaction::ConsensusCommitPrologueV3; - use crate::types::transaction::EndOfEpochTransactionKind; - use crate::types::transaction::GenesisTransaction; - use crate::types::transaction::ProgrammableTransaction; - use crate::types::transaction::RandomnessStateUpdate; - use crate::types::transaction::TransactionKind; + use crate::types::transaction::{ + AuthenticatorStateUpdate, ChangeEpoch, ConsensusCommitPrologue, ConsensusCommitPrologueV2, + ConsensusCommitPrologueV3, EndOfEpochTransactionKind, GenesisTransaction, + ProgrammableTransaction, RandomnessStateUpdate, TransactionKind, + }; #[derive(serde_derive::Serialize)] #[serde(tag = "kind", rename_all = "snake_case")] @@ -332,10 +320,10 @@ mod transaction_kind { mod end_of_epoch { use super::*; - use crate::types::transaction::AuthenticatorStateExpire; - use crate::types::transaction::ChangeEpoch; - use crate::types::transaction::EndOfEpochTransactionKind; - use crate::types::CheckpointDigest; + use crate::types::{ + transaction::{AuthenticatorStateExpire, ChangeEpoch, EndOfEpochTransactionKind}, + CheckpointDigest, + }; #[derive(serde_derive::Serialize)] #[serde(tag = "kind", rename_all = "snake_case")] @@ -516,8 +504,7 @@ mod end_of_epoch { mod version_assignments { use super::*; - use crate::types::transaction::CancelledTransaction; - use crate::types::transaction::ConsensusDeterminedVersionAssignments; + use crate::types::transaction::{CancelledTransaction, ConsensusDeterminedVersionAssignments}; #[derive(serde_derive::Serialize)] #[serde(tag = "kind", rename_all = "snake_case")] @@ -607,9 +594,8 @@ mod version_assignments { } mod input_argument { - use crate::types::transaction::InputArgument; - use super::*; + use crate::types::transaction::InputArgument; #[derive(serde_derive::Serialize, serde_derive::Deserialize)] #[serde(tag = "type", rename_all = "snake_case")] @@ -862,15 +848,10 @@ mod argument { mod command { use super::*; - - use crate::types::transaction::Command; - use crate::types::transaction::MakeMoveVector; - use crate::types::transaction::MergeCoins; - use crate::types::transaction::MoveCall; - use crate::types::transaction::Publish; - use crate::types::transaction::SplitCoins; - use crate::types::transaction::TransferObjects; - use crate::types::transaction::Upgrade; + use crate::types::transaction::{ + Command, MakeMoveVector, MergeCoins, MoveCall, Publish, SplitCoins, TransferObjects, + Upgrade, + }; #[derive(serde_derive::Serialize)] #[serde(tag = "command", rename_all = "snake_case")] @@ -985,9 +966,10 @@ mod signed_transaction { use serde::ser::SerializeSeq; use super::*; - use crate::types::transaction::SignedTransaction; - use crate::types::transaction::Transaction; - use crate::types::UserSignature; + use crate::types::{ + transaction::{SignedTransaction, Transaction}, + UserSignature, + }; /// Intents are defined as: /// @@ -1003,7 +985,7 @@ mod signed_transaction { /// } /// /// enum AppId { - /// Sui = 0, + /// Iota = 0, /// Narwhal = 1, /// Consensus = 2, /// } @@ -1052,7 +1034,7 @@ mod signed_transaction { _ => { return Err(serde::de::Error::custom(format!( "invalid intent message ({scope}, {version}, {app})" - ))) + ))); } } @@ -1149,9 +1131,10 @@ mod signed_transaction { } mod transaction_expiration { - use crate::types::{EpochId, TransactionExpiration}; use serde::{Deserialize, Deserializer, Serialize, Serializer}; + use crate::types::{EpochId, TransactionExpiration}; + #[derive(serde_derive::Serialize, serde_derive::Deserialize)] #[serde(rename = "TransactionExpiration")] #[serde(rename_all = "lowercase")] @@ -1247,19 +1230,15 @@ mod transaction_expiration { #[cfg(test)] mod test { - use base64ct::Base64; - use base64ct::Encoding; - - use crate::types::transaction::Argument; - use crate::types::transaction::InputArgument; - use crate::types::transaction::Transaction; - use crate::types::ObjectDigest; - use crate::types::ObjectId; - use crate::types::ObjectReference; - + use base64ct::{Base64, Encoding}; #[cfg(target_arch = "wasm32")] use wasm_bindgen_test::wasm_bindgen_test as test; + use crate::types::{ + transaction::{Argument, InputArgument, Transaction}, + ObjectDigest, ObjectId, ObjectReference, + }; + #[test] fn argument() { let test_cases = [ diff --git a/crates/sui-sdk/src/types/transaction/unresolved.rs b/crates/iota-rust-sdk/src/types/transaction/unresolved.rs similarity index 91% rename from crates/sui-sdk/src/types/transaction/unresolved.rs rename to crates/iota-rust-sdk/src/types/transaction/unresolved.rs index 8acff69..e20bdf1 100644 --- a/crates/sui-sdk/src/types/transaction/unresolved.rs +++ b/crates/iota-rust-sdk/src/types/transaction/unresolved.rs @@ -1,10 +1,5 @@ -use crate::types::object::Version; -use crate::types::Address; -use crate::types::ObjectDigest; -use crate::types::ObjectId; - -use super::Command; -use super::TransactionExpiration; +use super::{Command, TransactionExpiration}; +use crate::types::{object::Version, Address, ObjectDigest, ObjectId}; // A potentially Unresolved user transaction #[cfg_attr( @@ -77,7 +72,8 @@ pub enum UnresolvedInputArgument { // A Move object, either immutable, or owned mutable. ImmutableOrOwned(UnresolvedObjectReference), // A Move object that's shared. - // SharedObject::mutable controls whether caller asks for a mutable reference to shared object. + // SharedObject::mutable controls whether caller asks for a mutable reference to shared + // object. Shared { object_id: ObjectId, #[cfg_attr( diff --git a/crates/sui-sdk/src/types/type_tag/mod.rs b/crates/iota-rust-sdk/src/types/type_tag/mod.rs similarity index 93% rename from crates/sui-sdk/src/types/type_tag/mod.rs rename to crates/iota-rust-sdk/src/types/type_tag/mod.rs index 6b7f18f..8bd5aac 100644 --- a/crates/sui-sdk/src/types/type_tag/mod.rs +++ b/crates/iota-rust-sdk/src/types/type_tag/mod.rs @@ -51,7 +51,7 @@ impl std::str::FromStr for TypeTag { } } -//TODO flesh out this error type +// TODO flesh out this error type #[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)] pub struct TypeParseError; @@ -126,14 +126,14 @@ pub struct StructTag { impl StructTag { pub fn gas_coin() -> Self { - let sui = Self { + let iota = Self { address: Address::TWO, - module: Identifier::new("sui").unwrap(), - name: Identifier::new("SUI").unwrap(), + module: Identifier::new("iota").unwrap(), + name: Identifier::new("IOTA").unwrap(), type_params: vec![], }; - Self::coin(TypeTag::Struct(Box::new(sui))) + Self::coin(TypeTag::Struct(Box::new(iota))) } pub fn coin(type_tag: TypeTag) -> Self { @@ -145,11 +145,11 @@ impl StructTag { } } - pub fn staked_sui() -> Self { + pub fn staked_iota() -> Self { Self { address: Address::THREE, module: Identifier::new("staking_pool").unwrap(), - name: Identifier::new("StakedSui").unwrap(), + name: Identifier::new("StakedIota").unwrap(), type_params: vec![], } } diff --git a/crates/sui-sdk/src/types/type_tag/parse.rs b/crates/iota-rust-sdk/src/types/type_tag/parse.rs similarity index 77% rename from crates/sui-sdk/src/types/type_tag/parse.rs rename to crates/iota-rust-sdk/src/types/type_tag/parse.rs index f7b8a65..354693d 100644 --- a/crates/sui-sdk/src/types/type_tag/parse.rs +++ b/crates/iota-rust-sdk/src/types/type_tag/parse.rs @@ -1,21 +1,15 @@ -use super::Address; -use super::Identifier; -use super::StructTag; -use super::TypeTag; - -use winnow::ascii::space0; -use winnow::combinator::alt; -use winnow::combinator::delimited; -use winnow::combinator::eof; -use winnow::combinator::opt; -use winnow::combinator::separated; -use winnow::stream::AsChar; -use winnow::token::one_of; -use winnow::token::take_while; -use winnow::PResult; -use winnow::Parser; - -// static ALLOWED_IDENTIFIERS: &str = r"(?:[a-zA-Z][a-zA-Z0-9_]*)|(?:_[a-zA-Z0-9_]+)"; +use winnow::{ + ascii::space0, + combinator::{alt, delimited, eof, opt, separated}, + stream::AsChar, + token::{one_of, take_while}, + PResult, Parser, +}; + +use super::{Address, Identifier, StructTag, TypeTag}; + +// static ALLOWED_IDENTIFIERS: &str = +// r"(?:[a-zA-Z][a-zA-Z0-9_]*)|(?:_[a-zA-Z0-9_]+)"; static MAX_IDENTIFIER_LENGTH: usize = 128; pub(super) fn parse_identifier(mut input: &str) -> PResult<&str> { @@ -102,16 +96,16 @@ fn generics(input: &mut &str) -> PResult> { separated(1.., delimited(space0, type_tag, space0), ",").parse_next(input) } -//TODO add proptests +// TODO add proptests #[cfg(test)] mod tests { - use super::*; - use std::str::FromStr; #[cfg(target_arch = "wasm32")] use wasm_bindgen_test::wasm_bindgen_test as test; + use super::*; + #[test] fn test_type_tag() { for s in &[ @@ -159,33 +153,33 @@ mod tests { #[test] fn test_parse_valid_struct_type() { let valid = vec![ - "0x1::Foo::Foo", - "0x1::Foo_Type::Foo", - "0x1::Foo_::Foo", - "0x1::X_123::X32_", - "0x1::Foo::Foo_Type", - "0x1::Foo::Foo<0x1::ABC::ABC>", - "0x1::Foo::Foo<0x1::ABC::ABC_Type>", - "0x1::Foo::Foo", - "0x1::Foo::Foo", - "0x1::Foo::Foo", - "0x1::Foo::Foo", - "0x1::Foo::Foo", - "0x1::Foo::Foo", - "0x1::Foo::Foo", - "0x1::Foo::Foo
", - "0x1::Foo::Foo", - "0x1::Foo::Foo>", - "0x1::Foo::Foo", - "0x1::Foo::Foo", - "0x1::Foo::Foo", - "0x1::Foo::Foo,address,signer>", - "0x1::Foo::Foo>>", - "0x1::Foo::Foo<0x1::Foo::Struct, 0x1::Foo::Foo>>>>", - "0x1::_bar::_BAR", - "0x1::__::__", - "0x1::_bar::_BAR<0x2::_____::______fooo______>", - "0x1::__::__<0x2::_____::______fooo______, 0xff::Bar____::_______foo>", + "0x1::Foo::Foo", + "0x1::Foo_Type::Foo", + "0x1::Foo_::Foo", + "0x1::X_123::X32_", + "0x1::Foo::Foo_Type", + "0x1::Foo::Foo<0x1::ABC::ABC>", + "0x1::Foo::Foo<0x1::ABC::ABC_Type>", + "0x1::Foo::Foo", + "0x1::Foo::Foo", + "0x1::Foo::Foo", + "0x1::Foo::Foo", + "0x1::Foo::Foo", + "0x1::Foo::Foo", + "0x1::Foo::Foo", + "0x1::Foo::Foo
", + "0x1::Foo::Foo", + "0x1::Foo::Foo>", + "0x1::Foo::Foo", + "0x1::Foo::Foo", + "0x1::Foo::Foo", + "0x1::Foo::Foo,address,signer>", + "0x1::Foo::Foo>>", + "0x1::Foo::Foo<0x1::Foo::Struct, 0x1::Foo::Foo>>>>", + "0x1::_bar::_BAR", + "0x1::__::__", + "0x1::_bar::_BAR<0x2::_____::______fooo______>", + "0x1::__::__<0x2::_____::______fooo______, 0xff::Bar____::_______foo>", ]; for s in valid { let mut input = s; diff --git a/crates/sui-sdk/src/types/type_tag/serialization.rs b/crates/iota-rust-sdk/src/types/type_tag/serialization.rs similarity index 96% rename from crates/sui-sdk/src/types/type_tag/serialization.rs rename to crates/iota-rust-sdk/src/types/type_tag/serialization.rs index 4ce0547..eded71b 100644 --- a/crates/sui-sdk/src/types/type_tag/serialization.rs +++ b/crates/iota-rust-sdk/src/types/type_tag/serialization.rs @@ -1,11 +1,7 @@ +use serde::{de::Visitor, Deserialize, Deserializer, Serialize, Serializer}; +use serde_with::{DeserializeAs, SerializeAs}; + use super::*; -use serde::de::Visitor; -use serde::Deserialize; -use serde::Deserializer; -use serde::Serialize; -use serde::Serializer; -use serde_with::DeserializeAs; -use serde_with::SerializeAs; impl Serialize for Identifier { fn serialize(&self, serializer: S) -> Result @@ -246,12 +242,12 @@ impl<'de> Deserialize<'de> for StructTag { #[cfg(feature = "schemars")] mod json_schema { + use schemars::{ + schema::{InstanceType, Metadata, SchemaObject, StringValidation}, + JsonSchema, + }; + use super::*; - use schemars::schema::InstanceType; - use schemars::schema::Metadata; - use schemars::schema::SchemaObject; - use schemars::schema::StringValidation; - use schemars::JsonSchema; pub(crate) static ALLOWED_IDENTIFIERS: &str = r"(?:[a-zA-Z][a-zA-Z0-9_]{0,127})|(?:_[a-zA-Z0-9_]{0,127})"; @@ -266,7 +262,7 @@ mod json_schema { metadata: Some(Box::new(Metadata { title: Some(Self::schema_name()), description: Some("A Move Identifier".to_owned()), - examples: vec![serde_json::json!("sui")], + examples: vec![serde_json::json!("iota")], ..Default::default() })), instance_type: Some(InstanceType::String.into()), @@ -310,7 +306,7 @@ mod json_schema { metadata: Some(Box::new(Metadata { title: Some(Self::schema_name()), description: Some("A Move StructTag".to_owned()), - examples: vec![serde_json::json!("0x2::coin::Coin<0x2::sui::SUI>")], + examples: vec![serde_json::json!("0x2::coin::Coin<0x2::iota::IOTA>")], ..Default::default() })), instance_type: Some(InstanceType::String.into()), @@ -323,13 +319,13 @@ mod json_schema { #[cfg(test)] mod test { - use super::*; - use std::str::FromStr; #[cfg(target_arch = "wasm32")] use wasm_bindgen_test::wasm_bindgen_test as test; + use super::*; + #[test] fn type_tag_fixture() { let expected = TypeTag::Struct(Box::new(StructTag { diff --git a/crates/sui-sdk/src/types/u256.rs b/crates/iota-rust-sdk/src/types/u256.rs similarity index 95% rename from crates/sui-sdk/src/types/u256.rs rename to crates/iota-rust-sdk/src/types/u256.rs index 5a0575c..a31ebed 100644 --- a/crates/sui-sdk/src/types/u256.rs +++ b/crates/iota-rust-sdk/src/types/u256.rs @@ -1,8 +1,9 @@ -// Before we can expose this in the public interface it likely needs to be wrapped so that the type -// from our dependency doesn't leak +// Before we can expose this in the public interface it likely needs to be +// wrapped so that the type from our dependency doesn't leak pub(crate) type U256 = bnum::BUintD8<32>; -// This is a constant time assert to ensure that the backing storage for U256 is 32 bytes long +// This is a constant time assert to ensure that the backing storage for U256 is +// 32 bytes long #[allow(unused)] const ASSERT_32_BYTES: () = { let u256 = U256::ZERO; @@ -10,7 +11,8 @@ const ASSERT_32_BYTES: () = { let _digits: &[u8; 32] = u256.digits(); }; -// This is a constant time assert to ensure endianness of the underlying storage is as expected +// This is a constant time assert to ensure endianness of the underlying storage +// is as expected #[allow(unused)] const ASSERT_ENDIANNESS: () = { const fn const_bytes_equal(lhs: &[u8], rhs: &[u8]) -> bool { @@ -63,15 +65,16 @@ const ASSERT_ENDIANNESS: () = { #[cfg(test)] mod test { - use super::*; + use std::str::FromStr; + use num_bigint::BigUint; use proptest::prelude::*; - use std::str::FromStr; use test_strategy::proptest; - #[cfg(target_arch = "wasm32")] use wasm_bindgen_test::wasm_bindgen_test as test; + use super::*; + #[test] fn endianness() { let one_platform = U256::ONE; diff --git a/crates/sui-sdk/src/types/mod.rs b/crates/sui-sdk/src/types/mod.rs deleted file mode 100644 index 678232e..0000000 --- a/crates/sui-sdk/src/types/mod.rs +++ /dev/null @@ -1,154 +0,0 @@ -mod address; -mod checkpoint; -mod crypto; -mod digest; -mod effects; -mod events; -mod execution_status; -pub mod framework; -mod gas; -mod object; -mod object_id; -mod transaction; -mod type_tag; -mod u256; - -pub use address::Address; -pub use checkpoint::CheckpointCommitment; -pub use checkpoint::CheckpointContents; -pub use checkpoint::CheckpointData; -pub use checkpoint::CheckpointSequenceNumber; -pub use checkpoint::CheckpointSummary; -pub use checkpoint::CheckpointTimestamp; -pub use checkpoint::CheckpointTransaction; -pub use checkpoint::CheckpointTransactionInfo; -pub use checkpoint::EndOfEpochData; -pub use checkpoint::EpochId; -pub use checkpoint::ProtocolVersion; -pub use checkpoint::SignedCheckpointSummary; -pub use checkpoint::StakeUnit; -pub use crypto::Bls12381PrivateKey; -pub use crypto::Bls12381PublicKey; -pub use crypto::Bls12381Signature; -pub use crypto::Bn254FieldElement; -pub use crypto::CircomG1; -pub use crypto::CircomG2; -pub use crypto::Claim; -pub use crypto::Ed25519PrivateKey; -pub use crypto::Ed25519PublicKey; -pub use crypto::Ed25519Signature; -pub use crypto::Jwk; -pub use crypto::JwkId; -pub use crypto::JwtDetails; -pub use crypto::MultisigAggregatedSignature; -pub use crypto::MultisigCommittee; -pub use crypto::MultisigMember; -pub use crypto::MultisigMemberPublicKey; -pub use crypto::MultisigMemberSignature; -pub use crypto::PasskeyAuthenticator; -pub use crypto::PasskeyPublicKey; -pub use crypto::Secp256k1PrivateKey; -pub use crypto::Secp256k1PublicKey; -pub use crypto::Secp256k1Signature; -pub use crypto::Secp256r1PrivateKey; -pub use crypto::Secp256r1PublicKey; -pub use crypto::Secp256r1Signature; -pub use crypto::SignatureScheme; -pub use crypto::SimpleSignature; -pub use crypto::UserSignature; -pub use crypto::ValidatorAggregatedSignature; -pub use crypto::ValidatorCommittee; -pub use crypto::ValidatorCommitteeMember; -pub use crypto::ValidatorSignature; -pub use crypto::ZkLoginAuthenticator; -pub use crypto::ZkLoginInputs; -pub use crypto::ZkLoginProof; -pub use crypto::ZkLoginPublicIdentifier; -pub use digest::CheckpointContentsDigest; -pub use digest::CheckpointDigest; -pub use digest::ConsensusCommitDigest; -pub use digest::Digest; -pub use digest::DigestParseError; -pub use digest::EffectsAuxiliaryDataDigest; -pub use digest::ObjectDigest; -pub use digest::TransactionDigest; -pub use digest::TransactionEffectsDigest; -pub use digest::TransactionEventsDigest; -pub use effects::ChangedObject; -pub use effects::EffectsObjectChange; -pub use effects::IdOperation; -pub use effects::ModifiedAtVersion; -pub use effects::ObjectIn; -pub use effects::ObjectOut; -pub use effects::ObjectReferenceWithOwner; -pub use effects::TransactionEffects; -pub use effects::TransactionEffectsV1; -pub use effects::TransactionEffectsV2; -pub use effects::UnchangedSharedKind; -pub use effects::UnchangedSharedObject; -pub use events::BalanceChange; -pub use events::Event; -pub use events::TransactionEvents; -pub use execution_status::CommandArgumentError; -pub use execution_status::ExecutionError; -pub use execution_status::ExecutionStatus; -pub use execution_status::MoveLocation; -pub use execution_status::PackageUpgradeError; -pub use execution_status::TypeArgumentError; -pub use gas::GasCostSummary; -pub use object::GenesisObject; -pub use object::Object; -pub use object::ObjectData; -pub use object::ObjectReference; -pub use object::ObjectType; -pub use object::Owner; -pub use object::TypeOrigin; -pub use object::UpgradeInfo; -pub use object::Version; -pub use object_id::ObjectId; -pub use transaction::ActiveJwk; -pub use transaction::Argument; -pub use transaction::AuthenticatorStateExpire; -pub use transaction::AuthenticatorStateUpdate; -pub use transaction::CancelledTransaction; -pub use transaction::ChangeEpoch; -pub use transaction::Command; -pub use transaction::ConsensusCommitPrologue; -pub use transaction::ConsensusCommitPrologueV2; -pub use transaction::ConsensusCommitPrologueV3; -pub use transaction::ConsensusDeterminedVersionAssignments; -pub use transaction::EndOfEpochTransactionKind; -pub use transaction::GasPayment; -pub use transaction::GenesisTransaction; -pub use transaction::InputArgument; -pub use transaction::MakeMoveVector; -pub use transaction::MergeCoins; -pub use transaction::MoveCall; -pub use transaction::ProgrammableTransaction; -pub use transaction::Publish; -pub use transaction::RandomnessStateUpdate; -pub use transaction::SignedTransaction; -pub use transaction::SplitCoins; -pub use transaction::SystemPackage; -pub use transaction::Transaction; -pub use transaction::TransactionExpiration; -pub use transaction::TransactionKind; -pub use transaction::TransferObjects; -pub use transaction::UnresolvedGasPayment; -pub use transaction::UnresolvedInputArgument; -pub use transaction::UnresolvedObjectReference; -pub use transaction::UnresolvedProgrammableTransaction; -pub use transaction::UnresolvedTransaction; -pub use transaction::Upgrade; -pub use transaction::VersionAssignment; -pub use type_tag::Identifier; -pub use type_tag::StructTag; -pub use type_tag::TypeParseError; -pub use type_tag::TypeTag; - -#[cfg(feature = "serde")] -#[cfg_attr(doc_cfg, doc(cfg(feature = "serde")))] -pub(crate) use transaction::SignedTransactionWithIntentMessage; - -#[cfg(test)] -mod serialization_proptests;