diff --git a/Cargo.lock b/Cargo.lock index 2f3681f3783..2d379688b09 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2223,6 +2223,12 @@ dependencies = [ "serde", ] +[[package]] +name = "capitalize" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6b5271031022835ee8c7582fe67403bd6cb3d962095787af7921027234bab5bf" + [[package]] name = "cargo-platform" version = "0.1.8" @@ -5830,6 +5836,7 @@ version = "0.1.0" dependencies = [ "anyhow", "bcs", + "capitalize", "iota-move-build", "iota-types", "move-binary-format", @@ -5839,6 +5846,7 @@ dependencies = [ "once_cell", "regex", "serde", + "serde_json", "tracing", ] diff --git a/crates/iota-framework/Cargo.toml b/crates/iota-framework/Cargo.toml index 58d46cf6f9f..b4a1b8eb157 100644 --- a/crates/iota-framework/Cargo.toml +++ b/crates/iota-framework/Cargo.toml @@ -21,7 +21,9 @@ move-core-types.workspace = true [build-dependencies] anyhow.workspace = true bcs.workspace = true +capitalize = "0.3.4" regex.workspace = true +serde_json.workspace = true iota-move-build.workspace = true diff --git a/crates/iota-framework/build.rs b/crates/iota-framework/build.rs index 51d3a5ea57b..ca8fdc7f2c1 100644 --- a/crates/iota-framework/build.rs +++ b/crates/iota-framework/build.rs @@ -9,12 +9,13 @@ use std::{ }; use anyhow::Result; +use capitalize::Capitalize; use iota_move_build::{BuildConfig, IotaPackageHooks}; use move_binary_format::CompiledModule; use move_compiler::editions::Edition; use move_package::{BuildConfig as MoveBuildConfig, LintFlag}; -const DOCS_DIR: &str = "docs"; +const DOCS_DIR: &str = "../../docs/content/references/framework/"; /// Save revision info to environment variable fn main() { @@ -196,21 +197,20 @@ fn build_packages_with_move_config( std::fs::remove_dir_all(DOCS_DIR).unwrap(); } let mut files_to_write = BTreeMap::new(); - relocate_docs( - deepbook_dir, - &deepbook_pkg.package.compiled_docs.unwrap(), - &mut files_to_write, - ); + create_category_file(system_dir); relocate_docs( system_dir, &system_pkg.package.compiled_docs.unwrap(), &mut files_to_write, ); + create_category_file(framework_dir); + create_category_file(stdlib_dir); relocate_docs( framework_dir, &framework_pkg.package.compiled_docs.unwrap(), &mut files_to_write, ); + create_category_file(stardust_dir); relocate_docs( stardust_dir, &stardust_pkg.package.compiled_docs.unwrap(), @@ -219,12 +219,36 @@ fn build_packages_with_move_config( for (fname, doc) in files_to_write { let mut dst_path = PathBuf::from(DOCS_DIR); dst_path.push(fname); - fs::create_dir_all(dst_path.parent().unwrap()).unwrap(); fs::write(dst_path, doc).unwrap(); } } } +/// Create a Docusaurus category file for the specified prefix. +fn create_category_file(prefix: &str) { + let mut path = PathBuf::from(DOCS_DIR).join(prefix); + fs::create_dir_all(path.clone()).unwrap(); + path.push("_category_.json"); + let label = prefix + .split('-') + .map(|w| w.capitalize()) + .collect::>() + .join(" "); + fs::write( + path, + serde_json::json!({ + "label": label, + "link": { + "type": "generated-index", + "slug": format!("/references/framework/{}", prefix), + "description": format!( + "Documentation for the modules in the iota/crates/iota-framework/packages/{prefix} crate. Select a module from the list to see its details." + ) + } + }).to_string() + ).unwrap() +} + /// Post process the generated docs so that they are in a format that can be /// consumed by docusaurus. /// * Flatten out the tree-like structure of the docs directory that we generate @@ -253,6 +277,7 @@ fn relocate_docs(prefix: &str, files: &[(String, String)], output: &mut BTreeMap let link_to_regex = regex::Regex::new(r#"([\s\S]*?)"#).unwrap(); let code_regex = regex::Regex::new(r"([\s\S]*?)<\/code>").unwrap(); let type_regex = regex::Regex::new(r"(\S*?)<(IOTA|SMR|0xabcded::soon::SOON|T)>").unwrap(); + let iota_system_regex = regex::Regex::new(r"((?:\.\.\/|\.\/)+)(iota_system)(\.md)").unwrap(); for (file_name, file_content) in files { let path = PathBuf::from(file_name); @@ -276,18 +301,32 @@ fn relocate_docs(prefix: &str, files: &[(String, String)], output: &mut BTreeMap // need to make sure that `to` path don't contain extensions in a later step. let content = link_to_regex.replace_all(&content, r#"$2"#); - // Escape `{` in and add new lines as this is a requirement from mdx + // Escape `{` in multi-line and add new lines as this is a requirement + // from mdx let content = code_regex.replace_all(&content, |caps: ®ex::Captures| { + let match_content = caps.get(0).unwrap().as_str(); let code_content = caps.get(1).unwrap().as_str(); - format!("\n{}", code_content.replace('{', "\\{")) + if match_content.lines().count() == 1 { + return match_content.to_string(); + } + format!("\n\n{}\n", code_content.replace('{', "\\{")) }); // Wrap types like '', '' and more in backticks as they are seen as // React components otherwise let content = type_regex.replace_all(&content, r#"`$1<$2>`"#); + // Add the iota-system directory to links containing iota_system.md + // This is a quite specific case, as docs of packages, that are not + // dependencies, are created in root, but this script moves them to a + // folder with the name of the package. So their links are not correct anymore. + // We could improve this by checking all links that, are not from dependencies, + // against a list of all paths and replace them accordingly. + let content = iota_system_regex.replace_all(&content, r#"${1}iota-system/$2$3"#); + let content = content - .replace("../../dependencies/", "../") + .replace("../../", "../") + .replace("../dependencies/", "../") .replace("dependencies/", "../") // Here we remove the extension from `to` property in Link tags .replace(".md", ""); @@ -298,8 +337,9 @@ fn relocate_docs(prefix: &str, files: &[(String, String)], output: &mut BTreeMap let title_type = caps.get(1).unwrap().as_str(); let name = caps.get(2).unwrap().as_str(); let anchor = name.replace("::", "_"); - format!("---\ntitle: {}`{}`\n---\nimport Link from '@docusaurus/Link';\n\n", title_type, name, anchor) - }).to_string() + // Remove backticks from title and add module name as sidebar label + format!("---\ntitle: {}{}\nsidebar_label: {}\n---\nimport Link from '@docusaurus/Link';\n\n", title_type, name, name.split("::").last().unwrap(), anchor) + }).to_string() }); } } diff --git a/crates/iota-framework/docs/deepbook/clob.mdx b/crates/iota-framework/docs/deepbook/clob.mdx deleted file mode 100644 index 38d9559aa50..00000000000 --- a/crates/iota-framework/docs/deepbook/clob.mdx +++ /dev/null @@ -1,2700 +0,0 @@ ---- -title: Module `0xdee9::clob` ---- -import Link from '@docusaurus/Link'; - - - - -- [Struct `PoolCreated`](#0xdee9_clob_PoolCreated) -- [Struct `OrderPlacedV2`](#0xdee9_clob_OrderPlacedV2) -- [Struct `OrderCanceled`](#0xdee9_clob_OrderCanceled) -- [Struct `OrderFilledV2`](#0xdee9_clob_OrderFilledV2) -- [Struct `Order`](#0xdee9_clob_Order) -- [Struct `TickLevel`](#0xdee9_clob_TickLevel) -- [Resource `Pool`](#0xdee9_clob_Pool) -- [Struct `OrderPlaced`](#0xdee9_clob_OrderPlaced) -- [Struct `OrderFilled`](#0xdee9_clob_OrderFilled) -- [Constants](#@Constants_0) -- [Function `destroy_empty_level`](#0xdee9_clob_destroy_empty_level) -- [Function `create_account`](#0xdee9_clob_create_account) -- [Function `create_pool`](#0xdee9_clob_create_pool) -- [Function `deposit_base`](#0xdee9_clob_deposit_base) -- [Function `deposit_quote`](#0xdee9_clob_deposit_quote) -- [Function `withdraw_base`](#0xdee9_clob_withdraw_base) -- [Function `withdraw_quote`](#0xdee9_clob_withdraw_quote) -- [Function `swap_exact_base_for_quote`](#0xdee9_clob_swap_exact_base_for_quote) -- [Function `swap_exact_quote_for_base`](#0xdee9_clob_swap_exact_quote_for_base) -- [Function `match_bid_with_quote_quantity`](#0xdee9_clob_match_bid_with_quote_quantity) -- [Function `match_bid`](#0xdee9_clob_match_bid) -- [Function `match_ask`](#0xdee9_clob_match_ask) -- [Function `place_market_order`](#0xdee9_clob_place_market_order) -- [Function `inject_limit_order`](#0xdee9_clob_inject_limit_order) -- [Function `place_limit_order`](#0xdee9_clob_place_limit_order) -- [Function `order_is_bid`](#0xdee9_clob_order_is_bid) -- [Function `emit_order_canceled`](#0xdee9_clob_emit_order_canceled) -- [Function `emit_order_filled`](#0xdee9_clob_emit_order_filled) -- [Function `cancel_order`](#0xdee9_clob_cancel_order) -- [Function `remove_order`](#0xdee9_clob_remove_order) -- [Function `cancel_all_orders`](#0xdee9_clob_cancel_all_orders) -- [Function `batch_cancel_order`](#0xdee9_clob_batch_cancel_order) -- [Function `list_open_orders`](#0xdee9_clob_list_open_orders) -- [Function `account_balance`](#0xdee9_clob_account_balance) -- [Function `get_market_price`](#0xdee9_clob_get_market_price) -- [Function `get_level2_book_status_bid_side`](#0xdee9_clob_get_level2_book_status_bid_side) -- [Function `get_level2_book_status_ask_side`](#0xdee9_clob_get_level2_book_status_ask_side) -- [Function `get_level2_book_status`](#0xdee9_clob_get_level2_book_status) -- [Function `get_order_status`](#0xdee9_clob_get_order_status) - - -

-use 0x1::option;
-use 0x1::type_name;
-use 0x2::balance;
-use 0x2::clock;
-use 0x2::coin;
-use 0x2::event;
-use 0x2::iota;
-use 0x2::linked_table;
-use 0x2::object;
-use 0x2::table;
-use 0x2::tx_context;
-use 0xdee9::critbit;
-use 0xdee9::custodian;
-use 0xdee9::math;
-
- - - - - -## Struct `PoolCreated` - -Emitted when a new pool is created - - -

-struct PoolCreated has copy, drop, store
-
- - - -
-Fields - - -
-
- -pool_id: object::ID -
-
- object ID of the newly created pool -
-
- -base_asset: type_name::TypeName -
-
- -
-
- -quote_asset: type_name::TypeName -
-
- -
-
- -taker_fee_rate: u64 -
-
- -
-
- -maker_rebate_rate: u64 -
-
- -
-
- -tick_size: u64 -
-
- -
-
- -lot_size: u64 -
-
- -
-
- - -
- - - -## Struct `OrderPlacedV2` - -Emitted when a maker order is injected into the order book. - - -

-struct OrderPlacedV2<BaseAsset, QuoteAsset> has copy, drop, store
-
- - - -
-Fields - - -
-
- -pool_id: object::ID -
-
- object ID of the pool the order was placed on -
-
- -order_id: u64 -
-
- ID of the order within the pool -
-
- -is_bid: bool -
-
- -
-
- -owner: object::ID -
-
- object ID of the -AccountCap that placed the order -
-
- -base_asset_quantity_placed: u64 -
-
- -
-
- -price: u64 -
-
- -
-
- -expire_timestamp: u64 -
-
- -
-
- - -
- - - -## Struct `OrderCanceled` - -Emitted when a maker order is canceled. - - -

-struct OrderCanceled<BaseAsset, QuoteAsset> has copy, drop, store
-
- - - -
-Fields - - -
-
- -pool_id: object::ID -
-
- object ID of the pool the order was placed on -
-
- -order_id: u64 -
-
- ID of the order within the pool -
-
- -is_bid: bool -
-
- -
-
- -owner: object::ID -
-
- object ID of the -AccountCap that placed the order -
-
- -base_asset_quantity_canceled: u64 -
-
- -
-
- -price: u64 -
-
- -
-
- - -
- - - -## Struct `OrderFilledV2` - -Emitted only when a maker order is filled. - - -

-struct OrderFilledV2<BaseAsset, QuoteAsset> has copy, drop, store
-
- - - -
-Fields - - -
-
- -pool_id: object::ID -
-
- object ID of the pool the order was placed on -
-
- -order_id: u64 -
-
- ID of the order within the pool -
-
- -is_bid: bool -
-
- -
-
- -owner: object::ID -
-
- object ID of the -AccountCap that placed the order -
-
- -total_quantity: u64 -
-
- -
-
- -base_asset_quantity_filled: u64 -
-
- -
-
- -base_asset_quantity_remaining: u64 -
-
- -
-
- -price: u64 -
-
- -
-
- -taker_commission: u64 -
-
- -
-
- -maker_rebates: u64 -
-
- -
-
- - -
- - - -## Struct `Order` - - - -

-struct Order has drop, store
-
- - - -
-Fields - - -
-
- -order_id: u64 -
-
- -
-
- -price: u64 -
-
- -
-
- -quantity: u64 -
-
- -
-
- -is_bid: bool -
-
- -
-
- -owner: object::ID -
-
- -
-
- -expire_timestamp: u64 -
-
- -
-
- - -
- - - -## Struct `TickLevel` - - - -

-struct TickLevel has store
-
- - - -
-Fields - - -
-
- -price: u64 -
-
- -
-
- -open_orders: linked_table::LinkedTable<u64, clob::Order> -
-
- -
-
- - -
- - - -## Resource `Pool` - - - -

-struct Pool<BaseAsset, QuoteAsset> has key
-
- - - -
-Fields - - -
-
- -id: object::UID -
-
- -
-
- -bids: critbit::CritbitTree<clob::TickLevel> -
-
- -
-
- -asks: critbit::CritbitTree<clob::TickLevel> -
-
- -
-
- -next_bid_order_id: u64 -
-
- -
-
- -next_ask_order_id: u64 -
-
- -
-
- -usr_open_orders: table::Table<object::ID, linked_table::LinkedTable<u64, u64>> -
-
- -
-
- -taker_fee_rate: u64 -
-
- -
-
- -maker_rebate_rate: u64 -
-
- -
-
- -tick_size: u64 -
-
- -
-
- -lot_size: u64 -
-
- -
-
- -base_custodian: custodian::Custodian<BaseAsset> -
-
- -
-
- -quote_custodian: custodian::Custodian<QuoteAsset> -
-
- -
-
- -creation_fee: balance::Balance<iota::IOTA> -
-
- -
-
- -base_asset_trading_fees: balance::Balance<BaseAsset> -
-
- -
-
- -quote_asset_trading_fees: balance::Balance<QuoteAsset> -
-
- -
-
- - -
- - - -## Struct `OrderPlaced` - -Deprecated since v1.0.0, use -OrderPlacedV2 instead. - - -

-struct OrderPlaced<BaseAsset, QuoteAsset> has copy, drop, store
-
- - - -
-Fields - - -
-
- -pool_id: object::ID -
-
- object ID of the pool the order was placed on -
-
- -order_id: u64 -
-
- ID of the order within the pool -
-
- -is_bid: bool -
-
- -
-
- -owner: object::ID -
-
- object ID of the -AccountCap that placed the order -
-
- -base_asset_quantity_placed: u64 -
-
- -
-
- -price: u64 -
-
- -
-
- - -
- - - -## Struct `OrderFilled` - -Deprecated since v1.0.0, use -OrderFilledV2 instead. - - -

-struct OrderFilled<BaseAsset, QuoteAsset> has copy, drop, store
-
- - - -
-Fields - - -
-
- -pool_id: object::ID -
-
- object ID of the pool the order was placed on -
-
- -order_id: u64 -
-
- ID of the order within the pool -
-
- -is_bid: bool -
-
- -
-
- -owner: object::ID -
-
- object ID of the -AccountCap that placed the order -
-
- -total_quantity: u64 -
-
- -
-
- -base_asset_quantity_filled: u64 -
-
- -
-
- -base_asset_quantity_remaining: u64 -
-
- -
-
- -price: u64 -
-
- -
-
- - -
- - - -## Constants - - - - - - -

-const FLOAT_SCALING: u64 = 1000000000;
-
- - - - - - - -

-const DEPRECATED: u64 = 0;
-
- - - - - - - -

-const EInsufficientBaseCoin: u64 = 7;
-
- - - - - - - -

-const EInsufficientQuoteCoin: u64 = 8;
-
- - - - - - - -

-const EInvalidExpireTimestamp: u64 = 19;
-
- - - - - - - -

-const EInvalidOrderId: u64 = 3;
-
- - - - - - - -

-const EInvalidPrice: u64 = 5;
-
- - - - - - - -

-const EInvalidQuantity: u64 = 6;
-
- - - - - - - -

-const EInvalidRestriction: u64 = 14;
-
- - - - - - - -

-const EInvalidTickPrice: u64 = 11;
-
- - - - - - - -

-const EInvalidUser: u64 = 12;
-
- - - - - - - -

-const EOrderCannotBeFullyFilled: u64 = 9;
-
- - - - - - - -

-const EOrderCannotBeFullyPassive: u64 = 10;
-
- - - - - - - -

-const EUnauthorizedCancel: u64 = 4;
-
- - - - - - - -

-const FILL_OR_KILL: u8 = 2;
-
- - - - - - - -

-const IMMEDIATE_OR_CANCEL: u8 = 1;
-
- - - - - - - -

-const MAX_PRICE: u64 = 9223372036854775808;
-
- - - - - - - -

-const MIN_ASK_ORDER_ID: u64 = 9223372036854775808;
-
- - - - - - - -

-const MIN_PRICE: u64 = 0;
-
- - - - - - - -

-const NO_RESTRICTION: u8 = 0;
-
- - - - - - - -

-const POST_OR_ABORT: u8 = 3;
-
- - - - - -## Function `destroy_empty_level` - - - -

-fun destroy_empty_level(level: clob::TickLevel)
-
- - - -
-Implementation - - -

-fun destroy_empty_level(level: TickLevel) \{
-    let TickLevel \{
-        price: _,
-        open_orders: orders,
-    } = level;
-
-    linked_table::destroy_empty(orders);
-}
-
- - - -
- - - -## Function `create_account` - - - -

-public fun create_account(_ctx: &mut tx_context::TxContext): custodian::AccountCap
-
- - - -
-Implementation - - -

-public fun create_account(_ctx: &mut TxContext): AccountCap \{
-    abort DEPRECATED
-}
-
- - - -
- - - -## Function `create_pool` - - - -

-public fun create_pool<BaseAsset, QuoteAsset>(_tick_size: u64, _lot_size: u64, _creation_fee: coin::Coin<iota::IOTA>, _ctx: &mut tx_context::TxContext)
-
- - - -
-Implementation - - -

-public fun create_pool<BaseAsset, QuoteAsset>(
-    _tick_size: u64,
-    _lot_size: u64,
-    _creation_fee: Coin<IOTA>,
-    _ctx: &mut TxContext,
-) \{
-    abort DEPRECATED
-}
-
- - - -
- - - -## Function `deposit_base` - - - -

-public fun deposit_base<BaseAsset, QuoteAsset>(pool: &mut clob::Pool<BaseAsset, QuoteAsset>, coin: coin::Coin<BaseAsset>, account_cap: &custodian::AccountCap)
-
- - - -
-Implementation - - -

-public fun deposit_base<BaseAsset, QuoteAsset>(
-    pool: &mut Pool<BaseAsset, QuoteAsset>,
-    coin: Coin<BaseAsset>,
-    account_cap: &AccountCap
-) \{
-    assert!(coin::value(&coin) != 0, EInsufficientBaseCoin);
-    custodian::increase_user_available_balance(
-        &mut pool.base_custodian,
-        object::id(account_cap),
-        coin::into_balance(coin)
-    )
-}
-
- - - -
- - - -## Function `deposit_quote` - - - -

-public fun deposit_quote<BaseAsset, QuoteAsset>(pool: &mut clob::Pool<BaseAsset, QuoteAsset>, coin: coin::Coin<QuoteAsset>, account_cap: &custodian::AccountCap)
-
- - - -
-Implementation - - -

-public fun deposit_quote<BaseAsset, QuoteAsset>(
-    pool: &mut Pool<BaseAsset, QuoteAsset>,
-    coin: Coin<QuoteAsset>,
-    account_cap: &AccountCap
-) \{
-    assert!(coin::value(&coin) != 0, EInsufficientQuoteCoin);
-    custodian::increase_user_available_balance(
-        &mut pool.quote_custodian,
-        object::id(account_cap),
-        coin::into_balance(coin)
-    )
-}
-
- - - -
- - - -## Function `withdraw_base` - - - -

-public fun withdraw_base<BaseAsset, QuoteAsset>(pool: &mut clob::Pool<BaseAsset, QuoteAsset>, quantity: u64, account_cap: &custodian::AccountCap, ctx: &mut tx_context::TxContext): coin::Coin<BaseAsset>
-
- - - -
-Implementation - - -

-public fun withdraw_base<BaseAsset, QuoteAsset>(
-    pool: &mut Pool<BaseAsset, QuoteAsset>,
-    quantity: u64,
-    account_cap: &AccountCap,
-    ctx: &mut TxContext
-): Coin<BaseAsset> \{
-    assert!(quantity > 0, EInvalidQuantity);
-    custodian::withdraw_asset(&mut pool.base_custodian, quantity, account_cap, ctx)
-}
-
- - - -
- - - -## Function `withdraw_quote` - - - -

-public fun withdraw_quote<BaseAsset, QuoteAsset>(pool: &mut clob::Pool<BaseAsset, QuoteAsset>, quantity: u64, account_cap: &custodian::AccountCap, ctx: &mut tx_context::TxContext): coin::Coin<QuoteAsset>
-
- - - -
-Implementation - - -

-public fun withdraw_quote<BaseAsset, QuoteAsset>(
-    pool: &mut Pool<BaseAsset, QuoteAsset>,
-    quantity: u64,
-    account_cap: &AccountCap,
-    ctx: &mut TxContext
-): Coin<QuoteAsset> \{
-    assert!(quantity > 0, EInvalidQuantity);
-    custodian::withdraw_asset(&mut pool.quote_custodian, quantity, account_cap, ctx)
-}
-
- - - -
- - - -## Function `swap_exact_base_for_quote` - - - -

-public fun swap_exact_base_for_quote<BaseAsset, QuoteAsset>(pool: &mut clob::Pool<BaseAsset, QuoteAsset>, quantity: u64, base_coin: coin::Coin<BaseAsset>, quote_coin: coin::Coin<QuoteAsset>, clock: &clock::Clock, ctx: &mut tx_context::TxContext): (coin::Coin<BaseAsset>, coin::Coin<QuoteAsset>, u64)
-
- - - -
-Implementation - - -

-public fun swap_exact_base_for_quote<BaseAsset, QuoteAsset>(
-    pool: &mut Pool<BaseAsset, QuoteAsset>,
-    quantity: u64,
-    base_coin: Coin<BaseAsset>,
-    quote_coin: Coin<QuoteAsset>,
-    clock: &Clock,
-    ctx: &mut TxContext,
-): (Coin<BaseAsset>, Coin<QuoteAsset>, u64) \{
-    assert!(quantity > 0, EInvalidQuantity);
-    assert!(coin::value(&base_coin) >= quantity, EInsufficientBaseCoin);
-    let original_val = coin::value("e_coin);
-    let (ret_base_coin, ret_quote_coin) = place_market_order(
-        pool,
-        quantity,
-        false,
-        base_coin,
-        quote_coin,
-        clock,
-        ctx
-    );
-    let ret_val = coin::value(&ret_quote_coin);
-    (ret_base_coin, ret_quote_coin, ret_val - original_val)
-}
-
- - - -
- - - -## Function `swap_exact_quote_for_base` - - - -

-public fun swap_exact_quote_for_base<BaseAsset, QuoteAsset>(pool: &mut clob::Pool<BaseAsset, QuoteAsset>, quantity: u64, clock: &clock::Clock, quote_coin: coin::Coin<QuoteAsset>, ctx: &mut tx_context::TxContext): (coin::Coin<BaseAsset>, coin::Coin<QuoteAsset>, u64)
-
- - - -
-Implementation - - -

-public fun swap_exact_quote_for_base<BaseAsset, QuoteAsset>(
-    pool: &mut Pool<BaseAsset, QuoteAsset>,
-    quantity: u64,
-    clock: &Clock,
-    quote_coin: Coin<QuoteAsset>,
-    ctx: &mut TxContext,
-): (Coin<BaseAsset>, Coin<QuoteAsset>, u64) \{
-    assert!(quantity > 0, EInvalidQuantity);
-    assert!(coin::value("e_coin) >= quantity, EInsufficientQuoteCoin);
-    let (base_asset_balance, quote_asset_balance) = match_bid_with_quote_quantity(
-        pool,
-        quantity,
-        MAX_PRICE,
-        clock::timestamp_ms(clock),
-        coin::into_balance(quote_coin)
-    );
-    let val = balance::value(&base_asset_balance);
-    (coin::from_balance(base_asset_balance, ctx), coin::from_balance(quote_asset_balance, ctx), val)
-}
-
- - - -
- - - -## Function `match_bid_with_quote_quantity` - - - -

-fun match_bid_with_quote_quantity<BaseAsset, QuoteAsset>(pool: &mut clob::Pool<BaseAsset, QuoteAsset>, quantity: u64, price_limit: u64, current_timestamp: u64, quote_balance: balance::Balance<QuoteAsset>): (balance::Balance<BaseAsset>, balance::Balance<QuoteAsset>)
-
- - - -
-Implementation - - -

-fun match_bid_with_quote_quantity<BaseAsset, QuoteAsset>(
-    pool: &mut Pool<BaseAsset, QuoteAsset>,
-    quantity: u64,
-    price_limit: u64,
-    current_timestamp: u64,
-    quote_balance: Balance<QuoteAsset>,
-): (Balance<BaseAsset>, Balance<QuoteAsset>) \{
-    // Base balance received by taker, taking into account of taker commission.
-    // Need to individually keep track of the remaining base quantity to be filled to avoid infinite loop.
-    let pool_id = *object::uid_as_inner(&pool.id);
-    let mut taker_quote_quantity_remaining = quantity;
-    let mut base_balance_filled = balance::zero<BaseAsset>();
-    let mut quote_balance_left = quote_balance;
-    let all_open_orders = &mut pool.asks;
-    if (critbit::is_empty(all_open_orders)) \{
-        return (base_balance_filled, quote_balance_left)
-    };
-    let (mut tick_price, mut tick_index) = min_leaf(all_open_orders);
-    let mut terminate_loop = false;
-
-    while (!is_empty<TickLevel>(all_open_orders) && tick_price <= price_limit) \{
-        let tick_level = borrow_mut_leaf_by_index(all_open_orders, tick_index);
-        let mut order_id = *option::borrow(linked_table::front(&tick_level.open_orders));
-
-        while (!linked_table::is_empty(&tick_level.open_orders)) \{
-            let maker_order = linked_table::borrow(&tick_level.open_orders, order_id);
-            let mut maker_base_quantity = maker_order.quantity;
-            let mut skip_order = false;
-
-            if (maker_order.expire_timestamp <= current_timestamp) \{
-                skip_order = true;
-                custodian::unlock_balance(&mut pool.base_custodian, maker_order.owner, maker_order.quantity);
-                emit_order_canceled<BaseAsset, QuoteAsset>(pool_id, maker_order);
-            } else \{
-                // Calculate how much quote asset (maker_quote_quantity) is required, including the commission, to fill the maker order.
-                let maker_quote_quantity_without_commission = clob_math::mul(
-                    maker_base_quantity,
-                    maker_order.price
-                );
-                let (is_round_down, mut taker_commission)  = clob_math::unsafe_mul_round(
-                    maker_quote_quantity_without_commission,
-                    pool.taker_fee_rate
-                );
-                if (is_round_down)  taker_commission = taker_commission + 1;
-
-                let maker_quote_quantity = maker_quote_quantity_without_commission + taker_commission;
-
-                // Total base quantity filled.
-                let mut filled_base_quantity: u64;
-                // Total quote quantity filled, excluding commission and rebate.
-                let mut filled_quote_quantity: u64;
-                // Total quote quantity paid by taker.
-                // filled_quote_quantity_without_commission * (FLOAT_SCALING + taker_fee_rate) = filled_quote_quantity
-                let mut filled_quote_quantity_without_commission: u64;
-                if (taker_quote_quantity_remaining > maker_quote_quantity) \{
-                    filled_quote_quantity = maker_quote_quantity;
-                    filled_quote_quantity_without_commission = maker_quote_quantity_without_commission;
-                    filled_base_quantity = maker_base_quantity;
-                } else \{
-                    terminate_loop = true;
-                    // if not enough quote quantity to pay for taker commission, then no quantity will be filled
-                    filled_quote_quantity_without_commission = clob_math::unsafe_div(
-                        taker_quote_quantity_remaining,
-                        FLOAT_SCALING + pool.taker_fee_rate
-                    );
-                    // filled_base_quantity = 0 is permitted since filled_quote_quantity_without_commission can be 0
-                    filled_base_quantity = clob_math::unsafe_div(
-                        filled_quote_quantity_without_commission,
-                        maker_order.price
-                    );
-                    let filled_base_lot = filled_base_quantity / pool.lot_size;
-                    filled_base_quantity = filled_base_lot * pool.lot_size;
-                    // filled_quote_quantity_without_commission = 0 is permitted here since filled_base_quantity could be 0
-                    filled_quote_quantity_without_commission = clob_math::unsafe_mul(
-                        filled_base_quantity,
-                        maker_order.price
-                    );
-                    // if taker_commission = 0 due to underflow, round it up to 1
-                    let (round_down, mut taker_commission) = clob_math::unsafe_mul_round(
-                        filled_quote_quantity_without_commission,
-                        pool.taker_fee_rate
-                    );
-                    if (round_down) \{
-                        taker_commission = taker_commission + 1;
-                    };
-                    filled_quote_quantity = filled_quote_quantity_without_commission + taker_commission;
-                };
-                // if maker_rebate = 0 due to underflow, maker will not receive a rebate
-                let maker_rebate = clob_math::unsafe_mul(
-                    filled_quote_quantity_without_commission,
-                    pool.maker_rebate_rate
-                );
-                maker_base_quantity = maker_base_quantity - filled_base_quantity;
-
-                // maker in ask side, decrease maker's locked base asset, increase maker's available quote asset
-                taker_quote_quantity_remaining = taker_quote_quantity_remaining - filled_quote_quantity;
-                let locked_base_balance = custodian::decrease_user_locked_balance<BaseAsset>(
-                    &mut pool.base_custodian,
-                    maker_order.owner,
-                    filled_base_quantity
-                );
-
-                let mut quote_balance_filled = balance::split(
-                    &mut quote_balance_left,
-                    filled_quote_quantity,
-                );
-                // Send quote asset including rebate to maker.
-                custodian::increase_user_available_balance<QuoteAsset>(
-                    &mut pool.quote_custodian,
-                    maker_order.owner,
-                    balance::split(
-                        &mut quote_balance_filled,
-                        maker_rebate + filled_quote_quantity_without_commission,
-                    ),
-                );
-                // Send remaining of commission - rebate to the protocol.
-                // commission - rebate = filled_quote_quantity_without_commission - filled_quote_quantity - maker_rebate
-                balance::join(&mut pool.quote_asset_trading_fees, quote_balance_filled);
-                balance::join(&mut base_balance_filled, locked_base_balance);
-
-                emit_order_filled<BaseAsset, QuoteAsset>(
-                    *object::uid_as_inner(&pool.id),
-                    maker_order,
-                    filled_base_quantity,
-                    // taker_commission = filled_quote_quantity - filled_quote_quantity_without_commission
-                    // This guarantees that the subtraction will not underflow
-                    filled_quote_quantity - filled_quote_quantity_without_commission,
-                    maker_rebate
-                )
-            };
-
-            if (skip_order || maker_base_quantity == 0) \{
-                // Remove the maker order.
-                let old_order_id = order_id;
-                let maybe_order_id = linked_table::next(&tick_level.open_orders, order_id);
-                if (!option::is_none(maybe_order_id)) \{
-                    order_id = *option::borrow(maybe_order_id);
-                };
-                let usr_open_order_ids = table::borrow_mut(&mut pool.usr_open_orders, maker_order.owner);
-                linked_table::remove(usr_open_order_ids, old_order_id);
-                linked_table::remove(&mut tick_level.open_orders, old_order_id);
-            } else \{
-                // Update the maker order.
-                let maker_order_mut = linked_table::borrow_mut(
-                    &mut tick_level.open_orders,
-                    order_id);
-                maker_order_mut.quantity = maker_base_quantity;
-            };
-            if (terminate_loop) \{
-                break
-            };
-        };
-        if (linked_table::is_empty(&tick_level.open_orders)) \{
-            (tick_price, _) = next_leaf(all_open_orders, tick_price);
-            destroy_empty_level(remove_leaf_by_index(all_open_orders, tick_index));
-            (_, tick_index) = find_leaf(all_open_orders, tick_price);
-        };
-        if (terminate_loop) \{
-            break
-        };
-    };
-    return (base_balance_filled, quote_balance_left)
-}
-
- - - -
- - - -## Function `match_bid` - - - -

-fun match_bid<BaseAsset, QuoteAsset>(pool: &mut clob::Pool<BaseAsset, QuoteAsset>, quantity: u64, price_limit: u64, current_timestamp: u64, quote_balance: balance::Balance<QuoteAsset>): (balance::Balance<BaseAsset>, balance::Balance<QuoteAsset>)
-
- - - -
-Implementation - - -

-fun match_bid<BaseAsset, QuoteAsset>(
-    pool: &mut Pool<BaseAsset, QuoteAsset>,
-    quantity: u64,
-    price_limit: u64,
-    current_timestamp: u64,
-    quote_balance: Balance<QuoteAsset>,
-): (Balance<BaseAsset>, Balance<QuoteAsset>) \{
-    let pool_id = *object::uid_as_inner(&pool.id);
-    // Base balance received by taker.
-    // Need to individually keep track of the remaining base quantity to be filled to avoid infinite loop.
-    let mut taker_base_quantity_remaining = quantity;
-    let mut base_balance_filled = balance::zero<BaseAsset>();
-    let mut quote_balance_left = quote_balance;
-    let all_open_orders = &mut pool.asks;
-    if (critbit::is_empty(all_open_orders)) \{
-        return (base_balance_filled, quote_balance_left)
-    };
-    let (mut tick_price, mut tick_index) = min_leaf(all_open_orders);
-
-    while (!is_empty<TickLevel>(all_open_orders) && tick_price <= price_limit) \{
-        let tick_level = borrow_mut_leaf_by_index(all_open_orders, tick_index);
-        let mut order_id = *option::borrow(linked_table::front(&tick_level.open_orders));
-
-        while (!linked_table::is_empty(&tick_level.open_orders)) \{
-            let maker_order = linked_table::borrow(&tick_level.open_orders, order_id);
-            let mut maker_base_quantity = maker_order.quantity;
-            let mut skip_order = false;
-
-            if (maker_order.expire_timestamp <= current_timestamp) \{
-                skip_order = true;
-                custodian::unlock_balance(&mut pool.base_custodian, maker_order.owner, maker_order.quantity);
-                emit_order_canceled<BaseAsset, QuoteAsset>(pool_id, maker_order);
-            } else \{
-                let filled_base_quantity =
-                    if (taker_base_quantity_remaining > maker_base_quantity) \{ maker_base_quantity }
-                    else \{ taker_base_quantity_remaining };
-
-                let filled_quote_quantity = clob_math::mul(filled_base_quantity, maker_order.price);
-
-                // if maker_rebate = 0 due to underflow, maker will not receive a rebate
-                let maker_rebate = clob_math::unsafe_mul(filled_quote_quantity, pool.maker_rebate_rate);
-                // if taker_commission = 0 due to underflow, round it up to 1
-                let (is_round_down, mut taker_commission) = clob_math::unsafe_mul_round(
-                    filled_quote_quantity,
-                    pool.taker_fee_rate
-                );
-                if (is_round_down) taker_commission = taker_commission + 1;
-
-                maker_base_quantity = maker_base_quantity - filled_base_quantity;
-
-                // maker in ask side, decrease maker's locked base asset, increase maker's available quote asset
-                taker_base_quantity_remaining = taker_base_quantity_remaining - filled_base_quantity;
-                let locked_base_balance = custodian::decrease_user_locked_balance<BaseAsset>(
-                    &mut pool.base_custodian,
-                    maker_order.owner,
-                    filled_base_quantity
-                );
-                let mut taker_commission_balance = balance::split(
-                    &mut quote_balance_left,
-                    taker_commission,
-                );
-                custodian::increase_user_available_balance<QuoteAsset>(
-                    &mut pool.quote_custodian,
-                    maker_order.owner,
-                    balance::split(
-                        &mut taker_commission_balance,
-                        maker_rebate,
-                    ),
-                );
-                balance::join(&mut pool.quote_asset_trading_fees, taker_commission_balance);
-                balance::join(&mut base_balance_filled, locked_base_balance);
-
-                custodian::increase_user_available_balance<QuoteAsset>(
-                    &mut pool.quote_custodian,
-                    maker_order.owner,
-                    balance::split(
-                        &mut quote_balance_left,
-                        filled_quote_quantity,
-                    ),
-                );
-
-                emit_order_filled<BaseAsset, QuoteAsset>(
-                    *object::uid_as_inner(&pool.id),
-                    maker_order,
-                    filled_base_quantity,
-                    taker_commission,
-                    maker_rebate
-                );
-            };
-
-            if (skip_order || maker_base_quantity == 0) \{
-                // Remove the maker order.
-                let old_order_id = order_id;
-                let maybe_order_id = linked_table::next(&tick_level.open_orders, order_id);
-                if (!option::is_none(maybe_order_id)) \{
-                    order_id = *option::borrow(maybe_order_id);
-                };
-                let usr_open_order_ids = table::borrow_mut(&mut pool.usr_open_orders, maker_order.owner);
-                linked_table::remove(usr_open_order_ids, old_order_id);
-                linked_table::remove(&mut tick_level.open_orders, old_order_id);
-            } else \{
-                // Update the maker order.
-                let maker_order_mut = linked_table::borrow_mut(
-                    &mut tick_level.open_orders,
-                    order_id);
-                maker_order_mut.quantity = maker_base_quantity;
-            };
-            if (taker_base_quantity_remaining == 0) \{
-                break
-            };
-        };
-        if (linked_table::is_empty(&tick_level.open_orders)) \{
-            (tick_price, _) = next_leaf(all_open_orders, tick_price);
-            destroy_empty_level(remove_leaf_by_index(all_open_orders, tick_index));
-            (_, tick_index) = find_leaf(all_open_orders, tick_price);
-        };
-        if (taker_base_quantity_remaining == 0) \{
-            break
-        };
-    };
-    return (base_balance_filled, quote_balance_left)
-}
-
- - - -
- - - -## Function `match_ask` - - - -

-fun match_ask<BaseAsset, QuoteAsset>(pool: &mut clob::Pool<BaseAsset, QuoteAsset>, price_limit: u64, current_timestamp: u64, base_balance: balance::Balance<BaseAsset>): (balance::Balance<BaseAsset>, balance::Balance<QuoteAsset>)
-
- - - -
-Implementation - - -

-fun match_ask<BaseAsset, QuoteAsset>(
-    pool: &mut Pool<BaseAsset, QuoteAsset>,
-    price_limit: u64,
-    current_timestamp: u64,
-    base_balance: Balance<BaseAsset>,
-): (Balance<BaseAsset>, Balance<QuoteAsset>) \{
-    let pool_id = *object::uid_as_inner(&pool.id);
-    let mut base_balance_left = base_balance;
-    // Base balance received by taker, taking into account of taker commission.
-    let mut quote_balance_filled = balance::zero<QuoteAsset>();
-    let all_open_orders = &mut pool.bids;
-    if (critbit::is_empty(all_open_orders)) \{
-        return (base_balance_left, quote_balance_filled)
-    };
-    let (mut tick_price, mut tick_index) = max_leaf(all_open_orders);
-    while (!is_empty<TickLevel>(all_open_orders) && tick_price >= price_limit) \{
-        let tick_level = borrow_mut_leaf_by_index(all_open_orders, tick_index);
-        let mut order_id = *option::borrow(linked_table::front(&tick_level.open_orders));
-        while (!linked_table::is_empty(&tick_level.open_orders)) \{
-            let maker_order = linked_table::borrow(&tick_level.open_orders, order_id);
-            let mut maker_base_quantity = maker_order.quantity;
-            let mut skip_order = false;
-
-            if (maker_order.expire_timestamp <= current_timestamp) \{
-                skip_order = true;
-                let maker_quote_quantity = clob_math::mul(maker_order.quantity, maker_order.price);
-                custodian::unlock_balance(&mut pool.quote_custodian, maker_order.owner, maker_quote_quantity);
-                emit_order_canceled<BaseAsset, QuoteAsset>(pool_id, maker_order);
-            } else \{
-                let taker_base_quantity_remaining = balance::value(&base_balance_left);
-                let filled_base_quantity =
-                    if (taker_base_quantity_remaining >= maker_base_quantity) \{ maker_base_quantity }
-                    else \{ taker_base_quantity_remaining };
-
-                let filled_quote_quantity = clob_math::mul(filled_base_quantity, maker_order.price);
-
-                // if maker_rebate = 0 due to underflow, maker will not receive a rebate
-                let maker_rebate = clob_math::unsafe_mul(filled_quote_quantity, pool.maker_rebate_rate);
-                // if taker_commission = 0 due to underflow, round it up to 1
-                let (is_round_down, mut taker_commission) = clob_math::unsafe_mul_round(
-                    filled_quote_quantity,
-                    pool.taker_fee_rate
-                );
-                if (is_round_down) taker_commission = taker_commission + 1;
-
-                maker_base_quantity = maker_base_quantity - filled_base_quantity;
-                // maker in bid side, decrease maker's locked quote asset, increase maker's available base asset
-                let mut locked_quote_balance = custodian::decrease_user_locked_balance<QuoteAsset>(
-                    &mut pool.quote_custodian,
-                    maker_order.owner,
-                    filled_quote_quantity
-                );
-                let mut taker_commission_balance = balance::split(
-                    &mut locked_quote_balance,
-                    taker_commission,
-                );
-                custodian::increase_user_available_balance<QuoteAsset>(
-                    &mut pool.quote_custodian,
-                    maker_order.owner,
-                    balance::split(
-                        &mut taker_commission_balance,
-                        maker_rebate,
-                    ),
-                );
-                balance::join(&mut pool.quote_asset_trading_fees, taker_commission_balance);
-                balance::join(&mut quote_balance_filled, locked_quote_balance);
-
-                custodian::increase_user_available_balance<BaseAsset>(
-                    &mut pool.base_custodian,
-                    maker_order.owner,
-                    balance::split(
-                        &mut base_balance_left,
-                        filled_base_quantity,
-                    ),
-                );
-
-                emit_order_filled<BaseAsset, QuoteAsset>(
-                    *object::uid_as_inner(&pool.id),
-                    maker_order,
-                    filled_base_quantity,
-                    taker_commission,
-                    maker_rebate
-                );
-            };
-
-            if (skip_order || maker_base_quantity == 0) \{
-                // Remove the maker order.
-                let old_order_id = order_id;
-                let maybe_order_id = linked_table::next(&tick_level.open_orders, order_id);
-                if (!option::is_none(maybe_order_id)) \{
-                    order_id = *option::borrow(maybe_order_id);
-                };
-                let usr_open_order_ids = table::borrow_mut(&mut pool.usr_open_orders, maker_order.owner);
-                linked_table::remove(usr_open_order_ids, old_order_id);
-                linked_table::remove(&mut tick_level.open_orders, old_order_id);
-            } else \{
-                // Update the maker order.
-                let maker_order_mut = linked_table::borrow_mut(
-                    &mut tick_level.open_orders,
-                    order_id);
-                maker_order_mut.quantity = maker_base_quantity;
-            };
-            if (balance::value(&base_balance_left) == 0) \{
-                break
-            };
-        };
-        if (linked_table::is_empty(&tick_level.open_orders)) \{
-            (tick_price, _) = previous_leaf(all_open_orders, tick_price);
-            destroy_empty_level(remove_leaf_by_index(all_open_orders, tick_index));
-            (_, tick_index) = find_leaf(all_open_orders, tick_price);
-        };
-        if (balance::value(&base_balance_left) == 0) \{
-            break
-        };
-    };
-    return (base_balance_left, quote_balance_filled)
-}
-
- - - -
- - - -## Function `place_market_order` - -Place a market order to the order book. - - -

-public fun place_market_order<BaseAsset, QuoteAsset>(pool: &mut clob::Pool<BaseAsset, QuoteAsset>, quantity: u64, is_bid: bool, base_coin: coin::Coin<BaseAsset>, quote_coin: coin::Coin<QuoteAsset>, clock: &clock::Clock, ctx: &mut tx_context::TxContext): (coin::Coin<BaseAsset>, coin::Coin<QuoteAsset>)
-
- - - -
-Implementation - - -

-public fun place_market_order<BaseAsset, QuoteAsset>(
-    pool: &mut Pool<BaseAsset, QuoteAsset>,
-    quantity: u64,
-    is_bid: bool,
-    mut base_coin: Coin<BaseAsset>,
-    mut quote_coin: Coin<QuoteAsset>,
-    clock: &Clock,
-    ctx: &mut TxContext,
-): (Coin<BaseAsset>, Coin<QuoteAsset>) \{
-    // If market bid order, match against the open ask orders. Otherwise, match against the open bid orders.
-    // Take market bid order for example.
-    // We first retrieve the PriceLevel with the lowest price by calling min_leaf on the asks Critbit Tree.
-    // We then match the market order by iterating through open orders on that price level in ascending order of the order id.
-    // Open orders that are being filled are removed from the order book.
-    // We stop the iteration until all quantities are filled.
-    // If the total quantity of open orders at the lowest price level is not large enough to fully fill the market order,
-    // we move on to the next price level by calling next_leaf on the asks Critbit Tree and repeat the same procedure.
-    // Continue iterating over the price levels in ascending order until the market order is completely filled.
-    // If their market order cannot be completely filled even after consuming all the open ask orders,
-    // the unfilled quantity will be cancelled.
-    // Market ask order follows similar procedure.
-    // The difference is that market ask order is matched against the open bid orders.
-    // We start with the bid PriceLeve with the highest price by calling max_leaf on the bids Critbit Tree.
-    // The inner loop for iterating over the open orders in ascending orders of order id is the same as above.
-    // Then iterate over the price levels in descending order until the market order is completely filled.
-    assert!(quantity % pool.lot_size == 0, EInvalidQuantity);
-    assert!(quantity != 0, EInvalidQuantity);
-    if (is_bid) \{
-        let (base_balance_filled, quote_balance_left) = match_bid(
-            pool,
-            quantity,
-            MAX_PRICE,
-            clock::timestamp_ms(clock),
-            coin::into_balance(quote_coin),
-        );
-        join(
-            &mut base_coin,
-            coin::from_balance(base_balance_filled, ctx),
-        );
-        quote_coin = coin::from_balance(quote_balance_left, ctx);
-    } else \{
-        assert!(quantity <= coin::value(&base_coin), EInsufficientBaseCoin);
-        let (base_balance_left, quote_balance_filled) = match_ask(
-            pool,
-            MIN_PRICE,
-            clock::timestamp_ms(clock),
-            coin::into_balance(base_coin),
-        );
-        base_coin = coin::from_balance(base_balance_left, ctx);
-        join(
-            &mut quote_coin,
-            coin::from_balance(quote_balance_filled, ctx),
-        );
-    };
-    (base_coin, quote_coin)
-}
-
- - - -
- - - -## Function `inject_limit_order` - -Injects a maker order to the order book. -Returns the order id. - - -

-fun inject_limit_order<BaseAsset, QuoteAsset>(pool: &mut clob::Pool<BaseAsset, QuoteAsset>, price: u64, quantity: u64, is_bid: bool, expire_timestamp: u64, account_cap: &custodian::AccountCap, ctx: &mut tx_context::TxContext): u64
-
- - - -
-Implementation - - -

-fun inject_limit_order<BaseAsset, QuoteAsset>(
-    pool: &mut Pool<BaseAsset, QuoteAsset>,
-    price: u64,
-    quantity: u64,
-    is_bid: bool,
-    expire_timestamp: u64,
-    account_cap: &AccountCap,
-    ctx: &mut TxContext
-): u64 \{
-    let user = object::id(account_cap);
-    let order_id: u64;
-    let open_orders: &mut CritbitTree<TickLevel>;
-    if (is_bid) \{
-        let quote_quantity = clob_math::mul(quantity, price);
-        custodian::lock_balance<QuoteAsset>(&mut pool.quote_custodian, account_cap, quote_quantity);
-        order_id = pool.next_bid_order_id;
-        pool.next_bid_order_id = pool.next_bid_order_id + 1;
-        open_orders = &mut pool.bids;
-    } else \{
-        custodian::lock_balance<BaseAsset>(&mut pool.base_custodian, account_cap, quantity);
-        order_id = pool.next_ask_order_id;
-        pool.next_ask_order_id = pool.next_ask_order_id + 1;
-        open_orders = &mut pool.asks;
-    };
-    let order = Order \{
-        order_id,
-        price,
-        quantity,
-        is_bid,
-        owner: user,
-        expire_timestamp,
-    };
-    let (tick_exists, mut tick_index) = find_leaf(open_orders, price);
-    if (!tick_exists) \{
-        tick_index = insert_leaf(
-            open_orders,
-            price,
-            TickLevel \{
-                price,
-                open_orders: linked_table::new(ctx),
-            });
-    };
-
-    let tick_level = borrow_mut_leaf_by_index(open_orders, tick_index);
-    linked_table::push_back(&mut tick_level.open_orders, order_id, order);
-    event::emit(OrderPlacedV2<BaseAsset, QuoteAsset> \{
-        pool_id: *object::uid_as_inner(&pool.id),
-        order_id,
-        is_bid,
-        owner: user,
-        base_asset_quantity_placed: quantity,
-        price,
-        expire_timestamp
-    });
-    if (!contains(&pool.usr_open_orders, user)) \{
-        add(&mut pool.usr_open_orders, user, linked_table::new(ctx));
-    };
-    linked_table::push_back(borrow_mut(&mut pool.usr_open_orders, user), order_id, price);
-
-    return order_id
-}
-
- - - -
- - - -## Function `place_limit_order` - -Place a limit order to the order book. -Returns (base quantity filled, quote quantity filled, whether a maker order is being placed, order id of the maker order). -When the limit order is not successfully placed, we return false to indicate that and also returns a meaningless order_id 0. -When the limit order is successfully placed, we return true to indicate that and also the corresponding order_id. -So please check that boolean value first before using the order id. - - -

-public fun place_limit_order<BaseAsset, QuoteAsset>(pool: &mut clob::Pool<BaseAsset, QuoteAsset>, price: u64, quantity: u64, is_bid: bool, expire_timestamp: u64, restriction: u8, clock: &clock::Clock, account_cap: &custodian::AccountCap, ctx: &mut tx_context::TxContext): (u64, u64, bool, u64)
-
- - - -
-Implementation - - -

-public fun place_limit_order<BaseAsset, QuoteAsset>(
-    pool: &mut Pool<BaseAsset, QuoteAsset>,
-    price: u64,
-    quantity: u64,
-    is_bid: bool,
-    expire_timestamp: u64, // Expiration timestamp in ms in absolute value inclusive.
-    restriction: u8,
-    clock: &Clock,
-    account_cap: &AccountCap,
-    ctx: &mut TxContext
-): (u64, u64, bool, u64) \{
-    // If limit bid order, check whether the price is lower than the lowest ask order by checking the min_leaf of asks Critbit Tree.
-    // If so, assign the sequence id of the order to be next_bid_order_id and increment next_bid_order_id by 1.
-    // Inject the new order to the bids Critbit Tree according to the price and order id.
-    // Otherwise, find the price level from the asks Critbit Tree that is no greater than the input price.
-    // Match the bid order against the asks Critbit Tree in the same way as a market order but up until the price level found in the previous step.
-    // If the bid order is not completely filled, inject the remaining quantity to the bids Critbit Tree according to the input price and order id.
-    // If limit ask order, vice versa.
-    assert!(quantity > 0, EInvalidQuantity);
-    assert!(price > 0, EInvalidPrice);
-    assert!(price % pool.tick_size == 0, EInvalidPrice);
-    assert!(quantity % pool.lot_size == 0, EInvalidQuantity);
-    assert!(expire_timestamp > clock::timestamp_ms(clock), EInvalidExpireTimestamp);
-    let user = object::id(account_cap);
-    let base_quantity_filled;
-    let quote_quantity_filled;
-
-    if (is_bid) \{
-        let quote_quantity_original = custodian::account_available_balance<QuoteAsset>(
-            &pool.quote_custodian,
-            user,
-        );
-        let quote_balance = custodian::decrease_user_available_balance<QuoteAsset>(
-            &mut pool.quote_custodian,
-            account_cap,
-            quote_quantity_original,
-        );
-        let (base_balance_filled, quote_balance_left) = match_bid(
-            pool,
-            quantity,
-            price,
-            clock::timestamp_ms(clock),
-            quote_balance,
-        );
-        base_quantity_filled = balance::value(&base_balance_filled);
-        quote_quantity_filled = quote_quantity_original - balance::value("e_balance_left);
-
-        custodian::increase_user_available_balance<BaseAsset>(
-            &mut pool.base_custodian,
-            user,
-            base_balance_filled,
-        );
-        custodian::increase_user_available_balance<QuoteAsset>(
-            &mut pool.quote_custodian,
-            user,
-            quote_balance_left,
-        );
-    } else \{
-        let base_balance = custodian::decrease_user_available_balance<BaseAsset>(
-            &mut pool.base_custodian,
-            account_cap,
-            quantity,
-        );
-        let (base_balance_left, quote_balance_filled) = match_ask(
-            pool,
-            price,
-            clock::timestamp_ms(clock),
-            base_balance,
-        );
-
-        base_quantity_filled = quantity - balance::value(&base_balance_left);
-        quote_quantity_filled = balance::value("e_balance_filled);
-
-        custodian::increase_user_available_balance<BaseAsset>(
-            &mut pool.base_custodian,
-            user,
-            base_balance_left,
-        );
-        custodian::increase_user_available_balance<QuoteAsset>(
-            &mut pool.quote_custodian,
-            user,
-            quote_balance_filled,
-        );
-    };
-
-    let order_id;
-    if (restriction == IMMEDIATE_OR_CANCEL) \{
-        return (base_quantity_filled, quote_quantity_filled, false, 0)
-    };
-    if (restriction == FILL_OR_KILL) \{
-        assert!(base_quantity_filled == quantity, EOrderCannotBeFullyFilled);
-        return (base_quantity_filled, quote_quantity_filled, false, 0)
-    };
-    if (restriction == POST_OR_ABORT) \{
-        assert!(base_quantity_filled == 0, EOrderCannotBeFullyPassive);
-        order_id = inject_limit_order(pool, price, quantity, is_bid, expire_timestamp, account_cap, ctx);
-        return (base_quantity_filled, quote_quantity_filled, true, order_id)
-    } else \{
-        assert!(restriction == NO_RESTRICTION, EInvalidRestriction);
-        if (quantity > base_quantity_filled) \{
-            order_id = inject_limit_order(
-                pool,
-                price,
-                quantity - base_quantity_filled,
-                is_bid,
-                expire_timestamp,
-                account_cap,
-                ctx
-            );
-            return (base_quantity_filled, quote_quantity_filled, true, order_id)
-        };
-        return (base_quantity_filled, quote_quantity_filled, false, 0)
-    }
-}
-
- - - -
- - - -## Function `order_is_bid` - - - -

-fun order_is_bid(order_id: u64): bool
-
- - - -
-Implementation - - -

-fun order_is_bid(order_id: u64): bool \{
-    return order_id < MIN_ASK_ORDER_ID
-}
-
- - - -
- - - -## Function `emit_order_canceled` - - - -

-fun emit_order_canceled<BaseAsset, QuoteAsset>(pool_id: object::ID, order: &clob::Order)
-
- - - -
-Implementation - - -

-fun emit_order_canceled<BaseAsset, QuoteAsset>(
-    pool_id: ID,
-    order: &Order
-) \{
-    event::emit(OrderCanceled<BaseAsset, QuoteAsset> \{
-        pool_id,
-        order_id: order.order_id,
-        is_bid: order.is_bid,
-        owner: order.owner,
-        base_asset_quantity_canceled: order.quantity,
-        price: order.price
-    })
-}
-
- - - -
- - - -## Function `emit_order_filled` - - - -

-fun emit_order_filled<BaseAsset, QuoteAsset>(pool_id: object::ID, order: &clob::Order, base_asset_quantity_filled: u64, taker_commission: u64, maker_rebates: u64)
-
- - - -
-Implementation - - -

-fun emit_order_filled<BaseAsset, QuoteAsset>(
-    pool_id: ID,
-    order: &Order,
-    base_asset_quantity_filled: u64,
-    taker_commission: u64,
-    maker_rebates: u64
-) \{
-    event::emit(OrderFilledV2<BaseAsset, QuoteAsset> \{
-        pool_id,
-        order_id: order.order_id,
-        is_bid: order.is_bid,
-        owner: order.owner,
-        total_quantity: order.quantity,
-        base_asset_quantity_filled,
-        // order.quantity = base_asset_quantity_filled + base_asset_quantity_remaining
-        // This guarantees that the subtraction will not underflow
-        base_asset_quantity_remaining: order.quantity - base_asset_quantity_filled,
-        price: order.price,
-        taker_commission,
-        maker_rebates
-    })
-}
-
- - - -
- - - -## Function `cancel_order` - -Cancel and opening order. -Abort if order_id is invalid or if the order is not submitted by the transaction sender. - - -

-public fun cancel_order<BaseAsset, QuoteAsset>(pool: &mut clob::Pool<BaseAsset, QuoteAsset>, order_id: u64, account_cap: &custodian::AccountCap)
-
- - - -
-Implementation - - -

-public fun cancel_order<BaseAsset, QuoteAsset>(
-    pool: &mut Pool<BaseAsset, QuoteAsset>,
-    order_id: u64,
-    account_cap: &AccountCap
-) \{
-    // First check the highest bit of the order id to see whether it's bid or ask.
-    // Then retrieve the price using the order id.
-    // Using the price to retrieve the corresponding PriceLevel from the bids / asks Critbit Tree.
-    // Retrieve and remove the order from open orders of the PriceLevel.
-    let user = object::id(account_cap);
-    assert!(contains(&pool.usr_open_orders, user), EInvalidUser);
-    let usr_open_orders = borrow_mut(&mut pool.usr_open_orders, user);
-    assert!(linked_table::contains(usr_open_orders, order_id), EInvalidOrderId);
-    let tick_price = *linked_table::borrow(usr_open_orders, order_id);
-    let is_bid = order_is_bid(order_id);
-    let (tick_exists, tick_index) = find_leaf(
-        if (is_bid) \{ &pool.bids } else \{ &pool.asks },
-        tick_price);
-    assert!(tick_exists, EInvalidOrderId);
-    let order = remove_order(
-        if (is_bid) \{ &mut pool.bids } else \{ &mut pool.asks },
-        usr_open_orders,
-        tick_index,
-        order_id,
-        user
-    );
-    if (is_bid) \{
-        let balance_locked = clob_math::mul(order.quantity, order.price);
-        custodian::unlock_balance(&mut pool.quote_custodian, user, balance_locked);
-    } else \{
-        custodian::unlock_balance(&mut pool.base_custodian, user, order.quantity);
-    };
-    emit_order_canceled<BaseAsset, QuoteAsset>(*object::uid_as_inner(&pool.id), &order);
-}
-
- - - -
- - - -## Function `remove_order` - - - -

-fun remove_order(open_orders: &mut critbit::CritbitTree<clob::TickLevel>, usr_open_orders: &mut linked_table::LinkedTable<u64, u64>, tick_index: u64, order_id: u64, user: object::ID): clob::Order
-
- - - -
-Implementation - - -

-fun remove_order(
-    open_orders: &mut CritbitTree<TickLevel>,
-    usr_open_orders: &mut LinkedTable<u64, u64>,
-    tick_index: u64,
-    order_id: u64,
-    user: ID,
-): Order \{
-    linked_table::remove(usr_open_orders, order_id);
-    let tick_level = borrow_leaf_by_index(open_orders, tick_index);
-    assert!(linked_table::contains(&tick_level.open_orders, order_id), EInvalidOrderId);
-    let mut_tick_level = borrow_mut_leaf_by_index(open_orders, tick_index);
-    let order = linked_table::remove(&mut mut_tick_level.open_orders, order_id);
-    assert!(order.owner == user, EUnauthorizedCancel);
-    if (linked_table::is_empty(&mut_tick_level.open_orders)) \{
-        destroy_empty_level(remove_leaf_by_index(open_orders, tick_index));
-    };
-    order
-}
-
- - - -
- - - -## Function `cancel_all_orders` - - - -

-public fun cancel_all_orders<BaseAsset, QuoteAsset>(pool: &mut clob::Pool<BaseAsset, QuoteAsset>, account_cap: &custodian::AccountCap)
-
- - - -
-Implementation - - -

-public fun cancel_all_orders<BaseAsset, QuoteAsset>(
-    pool: &mut Pool<BaseAsset, QuoteAsset>,
-    account_cap: &AccountCap
-) \{
-    let pool_id = *object::uid_as_inner(&pool.id);
-    let user = object::id(account_cap);
-    assert!(contains(&pool.usr_open_orders, user), EInvalidUser);
-    let usr_open_order_ids = table::borrow_mut(&mut pool.usr_open_orders, user);
-    while (!linked_table::is_empty(usr_open_order_ids)) \{
-        let order_id = *option::borrow(linked_table::back(usr_open_order_ids));
-        let order_price = *linked_table::borrow(usr_open_order_ids, order_id);
-        let is_bid = order_is_bid(order_id);
-        let open_orders =
-            if (is_bid) \{ &mut pool.bids }
-            else \{ &mut pool.asks };
-        let (_, tick_index) = critbit::find_leaf(open_orders, order_price);
-        let order = remove_order(
-            open_orders,
-            usr_open_order_ids,
-            tick_index,
-            order_id,
-            user
-        );
-        if (is_bid) \{
-            let balance_locked = clob_math::mul(order.quantity, order.price);
-            custodian::unlock_balance(&mut pool.quote_custodian, user, balance_locked);
-        } else \{
-            custodian::unlock_balance(&mut pool.base_custodian, user, order.quantity);
-        };
-        emit_order_canceled<BaseAsset, QuoteAsset>(pool_id, &order);
-    };
-}
-
- - - -
- - - -## Function `batch_cancel_order` - -Batch cancel limit orders to save gas cost. -Abort if any of the order_ids are not submitted by the sender. -Skip any order_id that is invalid. -Note that this function can reduce gas cost even further if caller has multiple orders at the same price level, -and if orders with the same price are grouped together in the vector. -For example, if we have the following order_id to price mapping, \{0: 100., 1: 200., 2: 100., 3: 200.}. -Grouping order_ids like [0, 2, 1, 3] would make it the most gas efficient. - - -

-public fun batch_cancel_order<BaseAsset, QuoteAsset>(pool: &mut clob::Pool<BaseAsset, QuoteAsset>, order_ids: vector<u64>, account_cap: &custodian::AccountCap)
-
- - - -
-Implementation - - -

-public fun batch_cancel_order<BaseAsset, QuoteAsset>(
-    pool: &mut Pool<BaseAsset, QuoteAsset>,
-    order_ids: vector<u64>,
-    account_cap: &AccountCap
-) \{
-    let pool_id = *object::uid_as_inner(&pool.id);
-    // First group the order ids according to price level,
-    // so that we don't have to retrieve the PriceLevel multiple times if there are orders at the same price level.
-    // Iterate over each price level, retrieve the corresponding PriceLevel.
-    // Iterate over the order ids that need to be canceled at that price level,
-    // retrieve and remove the order from open orders of the PriceLevel.
-    let user = object::id(account_cap);
-    assert!(contains(&pool.usr_open_orders, user), 0);
-    let mut tick_index: u64 = 0;
-    let mut tick_price: u64 = 0;
-    let n_order = vector::length(&order_ids);
-    let mut i_order = 0;
-    let usr_open_orders = borrow_mut(&mut pool.usr_open_orders, user);
-    while (i_order < n_order) \{
-        let order_id = *vector::borrow(&order_ids, i_order);
-        assert!(linked_table::contains(usr_open_orders, order_id), EInvalidOrderId);
-        let new_tick_price = *linked_table::borrow(usr_open_orders, order_id);
-        let is_bid = order_is_bid(order_id);
-        if (new_tick_price != tick_price) \{
-            tick_price = new_tick_price;
-            let (tick_exists, new_tick_index) = find_leaf(
-                if (is_bid) \{ &pool.bids } else \{ &pool.asks },
-                tick_price
-            );
-            assert!(tick_exists, EInvalidTickPrice);
-            tick_index = new_tick_index;
-        };
-        let order = remove_order(
-            if (is_bid) \{ &mut pool.bids } else \{ &mut pool.asks },
-            usr_open_orders,
-            tick_index,
-            order_id,
-            user
-        );
-        if (is_bid) \{
-            let balance_locked = clob_math::mul(order.quantity, order.price);
-            custodian::unlock_balance(&mut pool.quote_custodian, user, balance_locked);
-        } else \{
-            custodian::unlock_balance(&mut pool.base_custodian, user, order.quantity);
-        };
-        emit_order_canceled<BaseAsset, QuoteAsset>(pool_id, &order);
-        i_order = i_order + 1;
-    }
-}
-
- - - -
- - - -## Function `list_open_orders` - - - -

-public fun list_open_orders<BaseAsset, QuoteAsset>(pool: &clob::Pool<BaseAsset, QuoteAsset>, account_cap: &custodian::AccountCap): vector<clob::Order>
-
- - - -
-Implementation - - -

-public fun list_open_orders<BaseAsset, QuoteAsset>(
-    pool: &Pool<BaseAsset, QuoteAsset>,
-    account_cap: &AccountCap
-): vector<Order> \{
-    let user = object::id(account_cap);
-    let usr_open_order_ids = table::borrow(&pool.usr_open_orders, user);
-    let mut open_orders = vector::empty<Order>();
-    let mut order_id = linked_table::front(usr_open_order_ids);
-    while (!option::is_none(order_id)) \{
-        let order_price = *linked_table::borrow(usr_open_order_ids, *option::borrow(order_id));
-        let tick_level =
-            if (order_is_bid(*option::borrow(order_id))) borrow_leaf_by_key(&pool.bids, order_price)
-            else borrow_leaf_by_key(&pool.asks, order_price);
-        let order = linked_table::borrow(&tick_level.open_orders, *option::borrow(order_id));
-        vector::push_back(&mut open_orders, Order \{
-            order_id: order.order_id,
-            price: order.price,
-            quantity: order.quantity,
-            is_bid: order.is_bid,
-            owner: order.owner,
-            expire_timestamp: order.expire_timestamp
-        });
-        order_id = linked_table::next(usr_open_order_ids, *option::borrow(order_id));
-    };
-    open_orders
-}
-
- - - -
- - - -## Function `account_balance` - -query user balance inside custodian - - -

-public fun account_balance<BaseAsset, QuoteAsset>(pool: &clob::Pool<BaseAsset, QuoteAsset>, account_cap: &custodian::AccountCap): (u64, u64, u64, u64)
-
- - - -
-Implementation - - -

-public fun account_balance<BaseAsset, QuoteAsset>(
-    pool: &Pool<BaseAsset, QuoteAsset>,
-    account_cap: &AccountCap
-): (u64, u64, u64, u64) \{
-    let user = object::id(account_cap);
-    let (base_avail, base_locked) = custodian::account_balance(&pool.base_custodian, user);
-    let (quote_avail, quote_locked) = custodian::account_balance(&pool.quote_custodian, user);
-    (base_avail, base_locked, quote_avail, quote_locked)
-}
-
- - - -
- - - -## Function `get_market_price` - -Query the market price of order book -returns (best_bid_price, best_ask_price) - - -

-public fun get_market_price<BaseAsset, QuoteAsset>(pool: &clob::Pool<BaseAsset, QuoteAsset>): (u64, u64)
-
- - - -
-Implementation - - -

-public fun get_market_price<BaseAsset, QuoteAsset>(
-    pool: &Pool<BaseAsset, QuoteAsset>
-): (u64, u64)\{
-    let (bid_price, _) = critbit::max_leaf(&pool.bids);
-    let (ask_price, _) = critbit::min_leaf(&pool.asks);
-    return (bid_price, ask_price)
-}
-
- - - -
- - - -## Function `get_level2_book_status_bid_side` - -Enter a price range and return the level2 order depth of all valid prices within this price range in bid side -returns two vectors of u64 -The previous is a list of all valid prices -The latter is the corresponding depth list - - -

-public fun get_level2_book_status_bid_side<BaseAsset, QuoteAsset>(pool: &clob::Pool<BaseAsset, QuoteAsset>, price_low: u64, price_high: u64, clock: &clock::Clock): (vector<u64>, vector<u64>)
-
- - - -
-Implementation - - -

-public fun get_level2_book_status_bid_side<BaseAsset, QuoteAsset>(
-    pool: &Pool<BaseAsset, QuoteAsset>,
-    mut price_low: u64,
-    mut price_high: u64,
-    clock: &Clock
-): (vector<u64>, vector<u64>) \{
-    let (price_low_, _) = critbit::min_leaf(&pool.bids);
-    if (price_low < price_low_) price_low = price_low_;
-    let (price_high_, _) = critbit::max_leaf(&pool.bids);
-    if (price_high > price_high_) price_high = price_high_;
-    price_low = critbit::find_closest_key(&pool.bids, price_low);
-    price_high = critbit::find_closest_key(&pool.bids, price_high);
-    let mut price_vec = vector::empty<u64>();
-    let mut depth_vec = vector::empty<u64>();
-    if (price_low == 0) \{ return (price_vec, depth_vec) };
-    while (price_low <= price_high) \{
-        let depth = get_level2_book_status(
-            &pool.bids,
-            price_low,
-            clock::timestamp_ms(clock)
-        );
-        vector::push_back(&mut price_vec, price_low);
-        vector::push_back(&mut depth_vec, depth);
-        let (next_price, _) = critbit::next_leaf(&pool.bids, price_low);
-        if (next_price == 0) \{ break }
-        else \{ price_low = next_price };
-    };
-    (price_vec, depth_vec)
-}
-
- - - -
- - - -## Function `get_level2_book_status_ask_side` - -Enter a price range and return the level2 order depth of all valid prices within this price range in ask side -returns two vectors of u64 -The previous is a list of all valid prices -The latter is the corresponding depth list - - -

-public fun get_level2_book_status_ask_side<BaseAsset, QuoteAsset>(pool: &clob::Pool<BaseAsset, QuoteAsset>, price_low: u64, price_high: u64, clock: &clock::Clock): (vector<u64>, vector<u64>)
-
- - - -
-Implementation - - -

-public fun get_level2_book_status_ask_side<BaseAsset, QuoteAsset>(
-    pool: &Pool<BaseAsset, QuoteAsset>,
-    mut price_low: u64,
-    mut price_high: u64,
-    clock: &Clock
-): (vector<u64>, vector<u64>) \{
-    let (price_low_, _) = critbit::min_leaf(&pool.asks);
-    if (price_low < price_low_) price_low = price_low_;
-    let (price_high_, _) = critbit::max_leaf(&pool.asks);
-    if (price_high > price_high_) price_high = price_high_;
-    price_low = critbit::find_closest_key(&pool.asks, price_low);
-    price_high = critbit::find_closest_key(&pool.asks, price_high);
-    let mut price_vec = vector::empty<u64>();
-    let mut depth_vec = vector::empty<u64>();
-    if (price_low == 0) \{ return (price_vec, depth_vec) };
-    while (price_low <= price_high) \{
-        let depth = get_level2_book_status(
-            &pool.asks,
-            price_low,
-            clock::timestamp_ms(clock)
-        );
-        vector::push_back(&mut price_vec, price_low);
-        vector::push_back(&mut depth_vec, depth);
-        let (next_price, _) = critbit::next_leaf(&pool.asks, price_low);
-        if (next_price == 0) \{ break }
-        else \{ price_low = next_price };
-    };
-    (price_vec, depth_vec)
-}
-
- - - -
- - - -## Function `get_level2_book_status` - -internal func to retrieve single depth of a tick price - - -

-fun get_level2_book_status(open_orders: &critbit::CritbitTree<clob::TickLevel>, price: u64, time_stamp: u64): u64
-
- - - -
-Implementation - - -

-fun get_level2_book_status(
-    open_orders: &CritbitTree<TickLevel>,
-    price: u64,
-    time_stamp: u64
-): u64 \{
-    let tick_level = critbit::borrow_leaf_by_key(open_orders, price);
-    let tick_open_orders = &tick_level.open_orders;
-    let mut depth = 0;
-    let mut order_id = linked_table::front(tick_open_orders);
-    let mut order: &Order;
-    while (!option::is_none(order_id)) \{
-        order = linked_table::borrow(tick_open_orders, *option::borrow(order_id));
-        if (order.expire_timestamp > time_stamp) depth = depth + order.quantity;
-        order_id = linked_table::next(tick_open_orders, *option::borrow(order_id));
-    };
-    depth
-}
-
- - - -
- - - -## Function `get_order_status` - - - -

-public fun get_order_status<BaseAsset, QuoteAsset>(pool: &clob::Pool<BaseAsset, QuoteAsset>, order_id: u64, account_cap: &custodian::AccountCap): &clob::Order
-
- - - -
-Implementation - - -

-public fun get_order_status<BaseAsset, QuoteAsset>(
-    pool: &Pool<BaseAsset, QuoteAsset>,
-    order_id: u64,
-    account_cap: &AccountCap
-): &Order \{
-    let user = object::id(account_cap);
-    assert!(table::contains(&pool.usr_open_orders, user), EInvalidUser);
-    let usr_open_order_ids = table::borrow(&pool.usr_open_orders, user);
-    assert!(linked_table::contains(usr_open_order_ids, order_id), EInvalidOrderId);
-    let order_price = *linked_table::borrow(usr_open_order_ids, order_id);
-    let open_orders =
-        if (order_id < MIN_ASK_ORDER_ID) \{ &pool.bids }
-        else \{ &pool.asks };
-    let tick_level = critbit::borrow_leaf_by_key(open_orders, order_price);
-    let tick_open_orders = &tick_level.open_orders;
-    let order = linked_table::borrow(tick_open_orders, order_id);
-    order
-}
-
- - - -
diff --git a/crates/iota-framework/docs/deepbook/clob_v2.mdx b/crates/iota-framework/docs/deepbook/clob_v2.mdx deleted file mode 100644 index 14e1387170f..00000000000 --- a/crates/iota-framework/docs/deepbook/clob_v2.mdx +++ /dev/null @@ -1,4766 +0,0 @@ ---- -title: Module `0xdee9::clob_v2` ---- -import Link from '@docusaurus/Link'; - - - - -- [Struct `PoolCreated`](#0xdee9_clob_v2_PoolCreated) -- [Struct `OrderPlaced`](#0xdee9_clob_v2_OrderPlaced) -- [Struct `OrderCanceled`](#0xdee9_clob_v2_OrderCanceled) -- [Struct `AllOrdersCanceledComponent`](#0xdee9_clob_v2_AllOrdersCanceledComponent) -- [Struct `AllOrdersCanceled`](#0xdee9_clob_v2_AllOrdersCanceled) -- [Struct `OrderFilled`](#0xdee9_clob_v2_OrderFilled) -- [Struct `DepositAsset`](#0xdee9_clob_v2_DepositAsset) -- [Struct `WithdrawAsset`](#0xdee9_clob_v2_WithdrawAsset) -- [Struct `MatchedOrderMetadata`](#0xdee9_clob_v2_MatchedOrderMetadata) -- [Struct `Order`](#0xdee9_clob_v2_Order) -- [Struct `TickLevel`](#0xdee9_clob_v2_TickLevel) -- [Resource `Pool`](#0xdee9_clob_v2_Pool) -- [Resource `PoolOwnerCap`](#0xdee9_clob_v2_PoolOwnerCap) -- [Constants](#@Constants_0) -- [Function `usr_open_orders_exist`](#0xdee9_clob_v2_usr_open_orders_exist) -- [Function `usr_open_orders_for_address`](#0xdee9_clob_v2_usr_open_orders_for_address) -- [Function `usr_open_orders`](#0xdee9_clob_v2_usr_open_orders) -- [Function `withdraw_fees`](#0xdee9_clob_v2_withdraw_fees) -- [Function `delete_pool_owner_cap`](#0xdee9_clob_v2_delete_pool_owner_cap) -- [Function `destroy_empty_level`](#0xdee9_clob_v2_destroy_empty_level) -- [Function `create_account`](#0xdee9_clob_v2_create_account) -- [Function `create_pool_`](#0xdee9_clob_v2_create_pool_) -- [Function `create_pool`](#0xdee9_clob_v2_create_pool) -- [Function `create_customized_pool`](#0xdee9_clob_v2_create_customized_pool) -- [Function `create_pool_with_return_`](#0xdee9_clob_v2_create_pool_with_return_) -- [Function `create_pool_with_return`](#0xdee9_clob_v2_create_pool_with_return) -- [Function `create_customized_pool_with_return`](#0xdee9_clob_v2_create_customized_pool_with_return) -- [Function `create_customized_pool_v2`](#0xdee9_clob_v2_create_customized_pool_v2) -- [Function `deposit_base`](#0xdee9_clob_v2_deposit_base) -- [Function `deposit_quote`](#0xdee9_clob_v2_deposit_quote) -- [Function `withdraw_base`](#0xdee9_clob_v2_withdraw_base) -- [Function `withdraw_quote`](#0xdee9_clob_v2_withdraw_quote) -- [Function `swap_exact_base_for_quote`](#0xdee9_clob_v2_swap_exact_base_for_quote) -- [Function `swap_exact_base_for_quote_with_metadata`](#0xdee9_clob_v2_swap_exact_base_for_quote_with_metadata) -- [Function `swap_exact_quote_for_base`](#0xdee9_clob_v2_swap_exact_quote_for_base) -- [Function `swap_exact_quote_for_base_with_metadata`](#0xdee9_clob_v2_swap_exact_quote_for_base_with_metadata) -- [Function `match_bid_with_quote_quantity`](#0xdee9_clob_v2_match_bid_with_quote_quantity) -- [Function `match_bid`](#0xdee9_clob_v2_match_bid) -- [Function `match_ask`](#0xdee9_clob_v2_match_ask) -- [Function `place_market_order`](#0xdee9_clob_v2_place_market_order) -- [Function `place_market_order_with_metadata`](#0xdee9_clob_v2_place_market_order_with_metadata) -- [Function `place_market_order_int`](#0xdee9_clob_v2_place_market_order_int) -- [Function `inject_limit_order`](#0xdee9_clob_v2_inject_limit_order) -- [Function `place_limit_order`](#0xdee9_clob_v2_place_limit_order) -- [Function `place_limit_order_with_metadata`](#0xdee9_clob_v2_place_limit_order_with_metadata) -- [Function `place_limit_order_int`](#0xdee9_clob_v2_place_limit_order_int) -- [Function `order_is_bid`](#0xdee9_clob_v2_order_is_bid) -- [Function `emit_order_canceled`](#0xdee9_clob_v2_emit_order_canceled) -- [Function `emit_order_filled`](#0xdee9_clob_v2_emit_order_filled) -- [Function `cancel_order`](#0xdee9_clob_v2_cancel_order) -- [Function `remove_order`](#0xdee9_clob_v2_remove_order) -- [Function `cancel_all_orders`](#0xdee9_clob_v2_cancel_all_orders) -- [Function `batch_cancel_order`](#0xdee9_clob_v2_batch_cancel_order) -- [Function `clean_up_expired_orders`](#0xdee9_clob_v2_clean_up_expired_orders) -- [Function `list_open_orders`](#0xdee9_clob_v2_list_open_orders) -- [Function `account_balance`](#0xdee9_clob_v2_account_balance) -- [Function `get_market_price`](#0xdee9_clob_v2_get_market_price) -- [Function `get_level2_book_status_bid_side`](#0xdee9_clob_v2_get_level2_book_status_bid_side) -- [Function `get_level2_book_status_ask_side`](#0xdee9_clob_v2_get_level2_book_status_ask_side) -- [Function `get_level2_book_status`](#0xdee9_clob_v2_get_level2_book_status) -- [Function `get_order_status`](#0xdee9_clob_v2_get_order_status) -- [Function `matched_order_metadata`](#0xdee9_clob_v2_matched_order_metadata) -- [Function `matched_order_metadata_info`](#0xdee9_clob_v2_matched_order_metadata_info) -- [Function `asks`](#0xdee9_clob_v2_asks) -- [Function `bids`](#0xdee9_clob_v2_bids) -- [Function `tick_size`](#0xdee9_clob_v2_tick_size) -- [Function `maker_rebate_rate`](#0xdee9_clob_v2_maker_rebate_rate) -- [Function `taker_fee_rate`](#0xdee9_clob_v2_taker_fee_rate) -- [Function `pool_size`](#0xdee9_clob_v2_pool_size) -- [Function `open_orders`](#0xdee9_clob_v2_open_orders) -- [Function `order_id`](#0xdee9_clob_v2_order_id) -- [Function `tick_level`](#0xdee9_clob_v2_tick_level) -- [Function `original_quantity`](#0xdee9_clob_v2_original_quantity) -- [Function `quantity`](#0xdee9_clob_v2_quantity) -- [Function `is_bid`](#0xdee9_clob_v2_is_bid) -- [Function `owner`](#0xdee9_clob_v2_owner) -- [Function `expire_timestamp`](#0xdee9_clob_v2_expire_timestamp) -- [Function `quote_asset_trading_fees_value`](#0xdee9_clob_v2_quote_asset_trading_fees_value) -- [Function `clone_order`](#0xdee9_clob_v2_clone_order) - - -

-use 0x1::option;
-use 0x1::type_name;
-use 0x1::vector;
-use 0x2::balance;
-use 0x2::clock;
-use 0x2::coin;
-use 0x2::event;
-use 0x2::iota;
-use 0x2::linked_table;
-use 0x2::object;
-use 0x2::table;
-use 0x2::transfer;
-use 0x2::tx_context;
-use 0xdee9::critbit;
-use 0xdee9::custodian_v2;
-use 0xdee9::math;
-
- - - - - -## Struct `PoolCreated` - -Emitted when a new pool is created - - -

-struct PoolCreated has copy, drop, store
-
- - - -
-Fields - - -
-
- -pool_id: object::ID -
-
- object ID of the newly created pool -
-
- -base_asset: type_name::TypeName -
-
- -
-
- -quote_asset: type_name::TypeName -
-
- -
-
- -taker_fee_rate: u64 -
-
- -
-
- -maker_rebate_rate: u64 -
-
- -
-
- -tick_size: u64 -
-
- -
-
- -lot_size: u64 -
-
- -
-
- - -
- - - -## Struct `OrderPlaced` - -Emitted when a maker order is injected into the order book. - - -

-struct OrderPlaced<BaseAsset, QuoteAsset> has copy, drop, store
-
- - - -
-Fields - - -
-
- -pool_id: object::ID -
-
- object ID of the pool the order was placed on -
-
- -order_id: u64 -
-
- ID of the order within the pool -
-
- -client_order_id: u64 -
-
- ID of the order defined by client -
-
- -is_bid: bool -
-
- -
-
- -owner: address -
-
- owner ID of the -AccountCap that placed the order -
-
- -original_quantity: u64 -
-
- -
-
- -base_asset_quantity_placed: u64 -
-
- -
-
- -price: u64 -
-
- -
-
- -expire_timestamp: u64 -
-
- -
-
- - -
- - - -## Struct `OrderCanceled` - -Emitted when a maker order is canceled. - - -

-struct OrderCanceled<BaseAsset, QuoteAsset> has copy, drop, store
-
- - - -
-Fields - - -
-
- -pool_id: object::ID -
-
- object ID of the pool the order was placed on -
-
- -order_id: u64 -
-
- ID of the order within the pool -
-
- -client_order_id: u64 -
-
- ID of the order defined by client -
-
- -is_bid: bool -
-
- -
-
- -owner: address -
-
- owner ID of the -AccountCap that canceled the order -
-
- -original_quantity: u64 -
-
- -
-
- -base_asset_quantity_canceled: u64 -
-
- -
-
- -price: u64 -
-
- -
-
- - -
- - - -## Struct `AllOrdersCanceledComponent` - -A struct to make all orders canceled a more effifient struct - - -

-struct AllOrdersCanceledComponent<BaseAsset, QuoteAsset> has copy, drop, store
-
- - - -
-Fields - - -
-
- -order_id: u64 -
-
- ID of the order within the pool -
-
- -client_order_id: u64 -
-
- ID of the order defined by client -
-
- -is_bid: bool -
-
- -
-
- -owner: address -
-
- owner ID of the -AccountCap that canceled the order -
-
- -original_quantity: u64 -
-
- -
-
- -base_asset_quantity_canceled: u64 -
-
- -
-
- -price: u64 -
-
- -
-
- - -
- - - -## Struct `AllOrdersCanceled` - -Emitted when batch of orders are canceled. - - -

-struct AllOrdersCanceled<BaseAsset, QuoteAsset> has copy, drop, store
-
- - - -
-Fields - - -
-
- -pool_id: object::ID -
-
- object ID of the pool the order was placed on -
-
- -orders_canceled: vector<clob_v2::AllOrdersCanceledComponent<BaseAsset, QuoteAsset>> -
-
- -
-
- - -
- - - -## Struct `OrderFilled` - -Emitted only when a maker order is filled. - - -

-struct OrderFilled<BaseAsset, QuoteAsset> has copy, drop, store
-
- - - -
-Fields - - -
-
- -pool_id: object::ID -
-
- object ID of the pool the order was placed on -
-
- -order_id: u64 -
-
- ID of the order within the pool -
-
- -taker_client_order_id: u64 -
-
- ID of the order defined by taker client -
-
- -maker_client_order_id: u64 -
-
- ID of the order defined by maker client -
-
- -is_bid: bool -
-
- -
-
- -taker_address: address -
-
- owner ID of the -AccountCap that filled the order -
-
- -maker_address: address -
-
- owner ID of the -AccountCap that placed the order -
-
- -original_quantity: u64 -
-
- -
-
- -base_asset_quantity_filled: u64 -
-
- -
-
- -base_asset_quantity_remaining: u64 -
-
- -
-
- -price: u64 -
-
- -
-
- -taker_commission: u64 -
-
- -
-
- -maker_rebates: u64 -
-
- -
-
- - -
- - - -## Struct `DepositAsset` - -Emitted when user deposit asset to custodian - - -

-struct DepositAsset<Asset> has copy, drop, store
-
- - - -
-Fields - - -
-
- -pool_id: object::ID -
-
- object id of the pool that asset deposit to -
-
- -quantity: u64 -
-
- quantity of the asset deposited -
-
- -owner: address -
-
- owner address of the -AccountCap that deposit the asset -
-
- - -
- - - -## Struct `WithdrawAsset` - -Emitted when user withdraw asset from custodian - - -

-struct WithdrawAsset<Asset> has copy, drop, store
-
- - - -
-Fields - - -
-
- -pool_id: object::ID -
-
- object id of the pool that asset withdraw from -
-
- -quantity: u64 -
-
- quantity of the asset user withdrew -
-
- -owner: address -
-
- owner ID of the -AccountCap that withdrew the asset -
-
- - -
- - - -## Struct `MatchedOrderMetadata` - -Returned as metadata only when a maker order is filled from place order functions. - - -

-struct MatchedOrderMetadata<BaseAsset, QuoteAsset> has copy, drop, store
-
- - - -
-Fields - - -
-
- -pool_id: object::ID -
-
- object ID of the pool the order was placed on -
-
- -order_id: u64 -
-
- ID of the order within the pool -
-
- -is_bid: bool -
-
- Direction of order. -
-
- -taker_address: address -
-
- owner ID of the -AccountCap that filled the order -
-
- -maker_address: address -
-
- owner ID of the -AccountCap that placed the order -
-
- -base_asset_quantity_filled: u64 -
-
- qty of base asset filled. -
-
- -price: u64 -
-
- price at which basset asset filled. -
-
- -taker_commission: u64 -
-
- -
-
- -maker_rebates: u64 -
-
- -
-
- - -
- - - -## Struct `Order` - - - -

-struct Order has drop, store
-
- - - -
-Fields - - -
-
- -order_id: u64 -
-
- -
-
- -client_order_id: u64 -
-
- -
-
- -price: u64 -
-
- -
-
- -original_quantity: u64 -
-
- -
-
- -quantity: u64 -
-
- -
-
- -is_bid: bool -
-
- -
-
- -owner: address -
-
- Order can only be canceled by the -AccountCap with this owner ID -
-
- -expire_timestamp: u64 -
-
- -
-
- -self_matching_prevention: u8 -
-
- -
-
- - -
- - - -## Struct `TickLevel` - - - -

-struct TickLevel has store
-
- - - -
-Fields - - -
-
- -price: u64 -
-
- -
-
- -open_orders: linked_table::LinkedTable<u64, clob_v2::Order> -
-
- -
-
- - -
- - - -## Resource `Pool` - - - -

-struct Pool<BaseAsset, QuoteAsset> has store, key
-
- - - -
-Fields - - -
-
- -id: object::UID -
-
- -
-
- -bids: critbit::CritbitTree<clob_v2::TickLevel> -
-
- -
-
- -asks: critbit::CritbitTree<clob_v2::TickLevel> -
-
- -
-
- -next_bid_order_id: u64 -
-
- -
-
- -next_ask_order_id: u64 -
-
- -
-
- -usr_open_orders: table::Table<address, linked_table::LinkedTable<u64, u64>> -
-
- -
-
- -taker_fee_rate: u64 -
-
- -
-
- -maker_rebate_rate: u64 -
-
- -
-
- -tick_size: u64 -
-
- -
-
- -lot_size: u64 -
-
- -
-
- -base_custodian: custodian_v2::Custodian<BaseAsset> -
-
- -
-
- -quote_custodian: custodian_v2::Custodian<QuoteAsset> -
-
- -
-
- -creation_fee: balance::Balance<iota::IOTA> -
-
- -
-
- -base_asset_trading_fees: balance::Balance<BaseAsset> -
-
- -
-
- -quote_asset_trading_fees: balance::Balance<QuoteAsset> -
-
- -
-
- - -
- - - -## Resource `PoolOwnerCap` - -Capability granting permission to access an entry in -Pool.quote_asset_trading_fees. -The pool objects created for older pools do not have a PoolOwnerCap because they were created -prior to the addition of this feature. Here is a list of 11 pools on mainnet that -do not have this capability: -0x31d1790e617eef7f516555124155b28d663e5c600317c769a75ee6336a54c07f -0x6e417ee1c12ad5f2600a66bc80c7bd52ff3cb7c072d508700d17cf1325324527 -0x17625f1a241d34d2da0dc113086f67a2b832e3e8cd8006887c195cd24d3598a3 -0x276ff4d99ecb3175091ba4baffa9b07590f84e2344e3f16e95d30d2c1678b84c -0xd1f0a9baacc1864ab19534e2d4c5d6c14f2e071a1f075e8e7f9d51f2c17dc238 -0x4405b50d791fd3346754e8171aaab6bc2ed26c2c46efdd033c14b30ae507ac33 -0xf0f663cf87f1eb124da2fc9be813e0ce262146f3df60bc2052d738eb41a25899 -0xd9e45ab5440d61cc52e3b2bd915cdd643146f7593d587c715bc7bfa48311d826 -0x5deafda22b6b86127ea4299503362638bea0ca33bb212ea3a67b029356b8b955 -0x7f526b1263c4b91b43c9e646419b5696f424de28dda3c1e6658cc0a54558baa7 -0x18d871e3c3da99046dfc0d3de612c5d88859bc03b8f0568bd127d0e70dbc58be - - -

-struct PoolOwnerCap has store, key
-
- - - -
-Fields - - -
-
- -id: object::UID -
-
- -
-
- -owner: address -
-
- The owner of this AccountCap. Note: this is - derived from an object ID, not a user address -
-
- - -
- - - -## Constants - - - - - - -

-const FLOAT_SCALING: u64 = 1000000000;
-
- - - - - - - -

-const EInsufficientBaseCoin: u64 = 7;
-
- - - - - - - -

-const EInsufficientQuoteCoin: u64 = 8;
-
- - - - - - - -

-const EInvalidExpireTimestamp: u64 = 19;
-
- - - - - - - -

-const EInvalidOrderId: u64 = 3;
-
- - - - - - - -

-const EInvalidPrice: u64 = 5;
-
- - - - - - - -

-const EInvalidQuantity: u64 = 6;
-
- - - - - - - -

-const EInvalidRestriction: u64 = 14;
-
- - - - - - - -

-const EInvalidTickPrice: u64 = 11;
-
- - - - - - - -

-const EInvalidUser: u64 = 12;
-
- - - - - - - -

-const EOrderCannotBeFullyFilled: u64 = 9;
-
- - - - - - - -

-const EOrderCannotBeFullyPassive: u64 = 10;
-
- - - - - - - -

-const EUnauthorizedCancel: u64 = 4;
-
- - - - - - - -

-const FILL_OR_KILL: u8 = 2;
-
- - - - - - - -

-const IMMEDIATE_OR_CANCEL: u8 = 1;
-
- - - - - - - -

-const MAX_PRICE: u64 = 9223372036854775808;
-
- - - - - - - -

-const MIN_ASK_ORDER_ID: u64 = 9223372036854775808;
-
- - - - - - - -

-const MIN_PRICE: u64 = 0;
-
- - - - - - - -

-const NO_RESTRICTION: u8 = 0;
-
- - - - - - - -

-const POST_OR_ABORT: u8 = 3;
-
- - - - - - - -

-const CANCEL_OLDEST: u8 = 0;
-
- - - - - - - -

-const EIncorrectPoolOwner: u64 = 1;
-
- - - - - - - -

-const EInvalidFee: u64 = 18;
-
- - - - - - - -

-const EInvalidFeeRateRebateRate: u64 = 2;
-
- - - - - - - -

-const EInvalidPair: u64 = 16;
-
- - - - - - - -

-const EInvalidSelfMatchingPreventionArg: u64 = 21;
-
- - - - - - - -

-const EInvalidTickSizeLotSize: u64 = 20;
-
- - - - - - - -

-const ENotEqual: u64 = 13;
-
- - - - - - - -

-const FEE_AMOUNT_FOR_CREATE_POOL: u64 = 100000000000;
-
- - - - - - - -

-const MIN_BID_ORDER_ID: u64 = 1;
-
- - - - - - - -

-const REFERENCE_MAKER_REBATE_RATE: u64 = 1500000;
-
- - - - - - - -

-const REFERENCE_TAKER_FEE_RATE: u64 = 2500000;
-
- - - - - -## Function `usr_open_orders_exist` - -Accessor functions - - -

-public fun usr_open_orders_exist<BaseAsset, QuoteAsset>(pool: &clob_v2::Pool<BaseAsset, QuoteAsset>, owner: address): bool
-
- - - -
-Implementation - - -

-public fun usr_open_orders_exist<BaseAsset, QuoteAsset>(
-    pool: &Pool<BaseAsset, QuoteAsset>,
-    owner: address
-): bool \{
-    table::contains(&pool.usr_open_orders, owner)
-}
-
- - - -
- - - -## Function `usr_open_orders_for_address` - - - -

-public fun usr_open_orders_for_address<BaseAsset, QuoteAsset>(pool: &clob_v2::Pool<BaseAsset, QuoteAsset>, owner: address): &linked_table::LinkedTable<u64, u64>
-
- - - -
-Implementation - - -

-public fun usr_open_orders_for_address<BaseAsset, QuoteAsset>(
-    pool: &Pool<BaseAsset, QuoteAsset>,
-    owner: address
-): &LinkedTable<u64, u64> \{
-    table::borrow(&pool.usr_open_orders, owner)
-}
-
- - - -
- - - -## Function `usr_open_orders` - - - -

-public fun usr_open_orders<BaseAsset, QuoteAsset>(pool: &clob_v2::Pool<BaseAsset, QuoteAsset>): &table::Table<address, linked_table::LinkedTable<u64, u64>>
-
- - - -
-Implementation - - -

-public fun usr_open_orders<BaseAsset, QuoteAsset>(
-    pool: &Pool<BaseAsset, QuoteAsset>,
-): &Table<address, LinkedTable<u64, u64>> \{
-    &pool.usr_open_orders
-}
-
- - - -
- - - -## Function `withdraw_fees` - -Function to withdraw fees created from a pool - - -

-public fun withdraw_fees<BaseAsset, QuoteAsset>(pool_owner_cap: &clob_v2::PoolOwnerCap, pool: &mut clob_v2::Pool<BaseAsset, QuoteAsset>, ctx: &mut tx_context::TxContext): coin::Coin<QuoteAsset>
-
- - - -
-Implementation - - -

-public fun withdraw_fees<BaseAsset, QuoteAsset>(
-    pool_owner_cap: &PoolOwnerCap,
-    pool: &mut Pool<BaseAsset, QuoteAsset>,
-    ctx: &mut TxContext,
-): Coin<QuoteAsset> \{
-    assert!(pool_owner_cap.owner == object::uid_to_address(&pool.id), EIncorrectPoolOwner);
-    let quantity = quote_asset_trading_fees_value(pool);
-    let to_withdraw = balance::split(&mut pool.quote_asset_trading_fees, quantity);
-    coin::from_balance(to_withdraw, ctx)
-}
-
- - - -
- - - -## Function `delete_pool_owner_cap` - -Destroy the given -pool_owner_cap object - - -

-public fun delete_pool_owner_cap(pool_owner_cap: clob_v2::PoolOwnerCap)
-
- - - -
-Implementation - - -

-public fun delete_pool_owner_cap(pool_owner_cap: PoolOwnerCap) \{
-    let PoolOwnerCap \{ id, owner: _ } = pool_owner_cap;
-    object::delete(id)
-}
-
- - - -
- - - -## Function `destroy_empty_level` - - - -

-fun destroy_empty_level(level: clob_v2::TickLevel)
-
- - - -
-Implementation - - -

-fun destroy_empty_level(level: TickLevel) \{
-    let TickLevel \{
-        price: _,
-        open_orders: orders,
-    } = level;
-
-    linked_table::destroy_empty(orders);
-}
-
- - - -
- - - -## Function `create_account` - - - -

-public fun create_account(ctx: &mut tx_context::TxContext): custodian_v2::AccountCap
-
- - - -
-Implementation - - -

-public fun create_account(ctx: &mut TxContext): AccountCap \{
-    mint_account_cap(ctx)
-}
-
- - - -
- - - -## Function `create_pool_` - - - -

-fun create_pool_<BaseAsset, QuoteAsset>(taker_fee_rate: u64, maker_rebate_rate: u64, tick_size: u64, lot_size: u64, creation_fee: balance::Balance<iota::IOTA>, ctx: &mut tx_context::TxContext)
-
- - - -
-Implementation - - -

-fun create_pool_<BaseAsset, QuoteAsset>(
-    taker_fee_rate: u64,
-    maker_rebate_rate: u64,
-    tick_size: u64,
-    lot_size: u64,
-    creation_fee: Balance<IOTA>,
-    ctx: &mut TxContext,
-) \{
-    let (pool, pool_owner_cap) = create_pool_with_return_<BaseAsset, QuoteAsset>(
-        taker_fee_rate,
-        maker_rebate_rate,
-        tick_size,
-        lot_size,
-        creation_fee,
-        ctx
-    );
-
-    transfer::public_transfer(pool_owner_cap, tx_context::sender(ctx));
-    transfer::share_object(pool);
-}
-
- - - -
- - - -## Function `create_pool` - - - -

-public fun create_pool<BaseAsset, QuoteAsset>(tick_size: u64, lot_size: u64, creation_fee: coin::Coin<iota::IOTA>, ctx: &mut tx_context::TxContext)
-
- - - -
-Implementation - - -

-public fun create_pool<BaseAsset, QuoteAsset>(
-    tick_size: u64,
-    lot_size: u64,
-    creation_fee: Coin<IOTA>,
-    ctx: &mut TxContext,
-) \{
-    create_customized_pool<BaseAsset, QuoteAsset>(
-        tick_size,
-        lot_size,
-        REFERENCE_TAKER_FEE_RATE,
-        REFERENCE_MAKER_REBATE_RATE,
-        creation_fee,
-        ctx,
-    );
-}
-
- - - -
- - - -## Function `create_customized_pool` - -Function for creating pool with customized taker fee rate and maker rebate rate. -The taker_fee_rate should be greater than or equal to the maker_rebate_rate, and both should have a scaling of 10^9. -Taker_fee_rate of 0.25% should be 2_500_000 for example - - -

-public fun create_customized_pool<BaseAsset, QuoteAsset>(tick_size: u64, lot_size: u64, taker_fee_rate: u64, maker_rebate_rate: u64, creation_fee: coin::Coin<iota::IOTA>, ctx: &mut tx_context::TxContext)
-
- - - -
-Implementation - - -

-public fun create_customized_pool<BaseAsset, QuoteAsset>(
-    tick_size: u64,
-    lot_size: u64,
-    taker_fee_rate: u64,
-    maker_rebate_rate: u64,
-    creation_fee: Coin<IOTA>,
-    ctx: &mut TxContext,
-) \{
-    create_pool_<BaseAsset, QuoteAsset>(
-        taker_fee_rate,
-        maker_rebate_rate,
-        tick_size,
-        lot_size,
-        coin::into_balance(creation_fee),
-        ctx
-    )
-}
-
- - - -
- - - -## Function `create_pool_with_return_` - -Helper function that all the create pools now call to create pools. - - -

-fun create_pool_with_return_<BaseAsset, QuoteAsset>(taker_fee_rate: u64, maker_rebate_rate: u64, tick_size: u64, lot_size: u64, creation_fee: balance::Balance<iota::IOTA>, ctx: &mut tx_context::TxContext): (clob_v2::Pool<BaseAsset, QuoteAsset>, clob_v2::PoolOwnerCap)
-
- - - -
-Implementation - - -

-fun create_pool_with_return_<BaseAsset, QuoteAsset>(
-    taker_fee_rate: u64,
-    maker_rebate_rate: u64,
-    tick_size: u64,
-    lot_size: u64,
-    creation_fee: Balance<IOTA>,
-    ctx: &mut TxContext,
-): (Pool<BaseAsset, QuoteAsset>, PoolOwnerCap) \{
-    assert!(balance::value(&creation_fee) == FEE_AMOUNT_FOR_CREATE_POOL, EInvalidFee);
-
-    let base_type_name = type_name::get<BaseAsset>();
-    let quote_type_name = type_name::get<QuoteAsset>();
-
-    assert!(clob_math::unsafe_mul(lot_size, tick_size) > 0, EInvalidTickSizeLotSize);
-    assert!(base_type_name != quote_type_name, EInvalidPair);
-    assert!(taker_fee_rate >= maker_rebate_rate, EInvalidFeeRateRebateRate);
-
-    let pool_uid = object::new(ctx);
-    let pool_id = *object::uid_as_inner(&pool_uid);
-
-    // Creates the capability to mark a pool owner.
-    let id = object::new(ctx);
-    let owner = object::uid_to_address(&pool_uid);
-    let pool_owner_cap = PoolOwnerCap \{ id, owner };
-
-    event::emit(PoolCreated \{
-        pool_id,
-        base_asset: base_type_name,
-        quote_asset: quote_type_name,
-        taker_fee_rate,
-        maker_rebate_rate,
-        tick_size,
-        lot_size,
-    });
-    (Pool<BaseAsset, QuoteAsset> \{
-        id: pool_uid,
-        bids: critbit::new(ctx),
-        asks: critbit::new(ctx),
-        next_bid_order_id: MIN_BID_ORDER_ID,
-        next_ask_order_id: MIN_ASK_ORDER_ID,
-        usr_open_orders: table::new(ctx),
-        taker_fee_rate,
-        maker_rebate_rate,
-        tick_size,
-        lot_size,
-        base_custodian: custodian::new<BaseAsset>(ctx),
-        quote_custodian: custodian::new<QuoteAsset>(ctx),
-        creation_fee,
-        base_asset_trading_fees: balance::zero(),
-        quote_asset_trading_fees: balance::zero(),
-    }, pool_owner_cap)
-}
-
- - - -
- - - -## Function `create_pool_with_return` - -Function for creating an external pool. This API can be used to wrap deepbook pools into other objects. - - -

-public fun create_pool_with_return<BaseAsset, QuoteAsset>(tick_size: u64, lot_size: u64, creation_fee: coin::Coin<iota::IOTA>, ctx: &mut tx_context::TxContext): clob_v2::Pool<BaseAsset, QuoteAsset>
-
- - - -
-Implementation - - -

-public fun create_pool_with_return<BaseAsset, QuoteAsset>(
-    tick_size: u64,
-    lot_size: u64,
-    creation_fee: Coin<IOTA>,
-    ctx: &mut TxContext,
-): Pool<BaseAsset, QuoteAsset> \{
-    create_customized_pool_with_return<BaseAsset, QuoteAsset>(
-        tick_size,
-        lot_size,
-        REFERENCE_TAKER_FEE_RATE,
-        REFERENCE_MAKER_REBATE_RATE,
-        creation_fee,
-        ctx,
-    )
-}
-
- - - -
- - - -## Function `create_customized_pool_with_return` - -Function for creating pool with customized taker fee rate and maker rebate rate. -The taker_fee_rate should be greater than or equal to the maker_rebate_rate, and both should have a scaling of 10^9. -Taker_fee_rate of 0.25% should be 2_500_000 for example - - -

-public fun create_customized_pool_with_return<BaseAsset, QuoteAsset>(tick_size: u64, lot_size: u64, taker_fee_rate: u64, maker_rebate_rate: u64, creation_fee: coin::Coin<iota::IOTA>, ctx: &mut tx_context::TxContext): clob_v2::Pool<BaseAsset, QuoteAsset>
-
- - - -
-Implementation - - -

-public fun create_customized_pool_with_return<BaseAsset, QuoteAsset>(
-    tick_size: u64,
-    lot_size: u64,
-    taker_fee_rate: u64,
-    maker_rebate_rate: u64,
-    creation_fee: Coin<IOTA>,
-    ctx: &mut TxContext,
-) : Pool<BaseAsset, QuoteAsset> \{
-    let (pool, pool_owner_cap) = create_pool_with_return_<BaseAsset, QuoteAsset>(
-        taker_fee_rate,
-        maker_rebate_rate,
-        tick_size,
-        lot_size,
-        coin::into_balance(creation_fee),
-        ctx
-    );
-    transfer::public_transfer(pool_owner_cap, tx_context::sender(ctx));
-    pool
-}
-
- - - -
- - - -## Function `create_customized_pool_v2` - -A V2 function for creating customized pools for better PTB friendliness/compostability. -If a user wants to create a pool and then destroy/lock the pool_owner_cap one can do -so with this function. - - -

-public fun create_customized_pool_v2<BaseAsset, QuoteAsset>(tick_size: u64, lot_size: u64, taker_fee_rate: u64, maker_rebate_rate: u64, creation_fee: coin::Coin<iota::IOTA>, ctx: &mut tx_context::TxContext): (clob_v2::Pool<BaseAsset, QuoteAsset>, clob_v2::PoolOwnerCap)
-
- - - -
-Implementation - - -

-public fun create_customized_pool_v2<BaseAsset, QuoteAsset>(
-    tick_size: u64,
-    lot_size: u64,
-    taker_fee_rate: u64,
-    maker_rebate_rate: u64,
-    creation_fee: Coin<IOTA>,
-    ctx: &mut TxContext,
-) : (Pool<BaseAsset, QuoteAsset>, PoolOwnerCap) \{
-    create_pool_with_return_<BaseAsset, QuoteAsset>(
-        taker_fee_rate,
-        maker_rebate_rate,
-        tick_size,
-        lot_size,
-        coin::into_balance(creation_fee),
-        ctx
-    )
-}
-
- - - -
- - - -## Function `deposit_base` - - - -

-public fun deposit_base<BaseAsset, QuoteAsset>(pool: &mut clob_v2::Pool<BaseAsset, QuoteAsset>, coin: coin::Coin<BaseAsset>, account_cap: &custodian_v2::AccountCap)
-
- - - -
-Implementation - - -

-public fun deposit_base<BaseAsset, QuoteAsset>(
-    pool: &mut Pool<BaseAsset, QuoteAsset>,
-    coin: Coin<BaseAsset>,
-    account_cap: &AccountCap
-) \{
-    let quantity = coin::value(&coin);
-    assert!(quantity != 0, EInsufficientBaseCoin);
-    custodian::increase_user_available_balance(
-        &mut pool.base_custodian,
-        account_owner(account_cap),
-        coin::into_balance(coin)
-    );
-    event::emit(DepositAsset<BaseAsset>\{
-        pool_id: *object::uid_as_inner(&pool.id),
-        quantity,
-        owner: account_owner(account_cap)
-    })
-}
-
- - - -
- - - -## Function `deposit_quote` - - - -

-public fun deposit_quote<BaseAsset, QuoteAsset>(pool: &mut clob_v2::Pool<BaseAsset, QuoteAsset>, coin: coin::Coin<QuoteAsset>, account_cap: &custodian_v2::AccountCap)
-
- - - -
-Implementation - - -

-public fun deposit_quote<BaseAsset, QuoteAsset>(
-    pool: &mut Pool<BaseAsset, QuoteAsset>,
-    coin: Coin<QuoteAsset>,
-    account_cap: &AccountCap
-) \{
-    let quantity = coin::value(&coin);
-    assert!(quantity != 0, EInsufficientQuoteCoin);
-    custodian::increase_user_available_balance(
-        &mut pool.quote_custodian,
-        account_owner(account_cap),
-        coin::into_balance(coin)
-    );
-    event::emit(DepositAsset<QuoteAsset>\{
-        pool_id: *object::uid_as_inner(&pool.id),
-        quantity,
-        owner: account_owner(account_cap)
-    })
-}
-
- - - -
- - - -## Function `withdraw_base` - - - -

-public fun withdraw_base<BaseAsset, QuoteAsset>(pool: &mut clob_v2::Pool<BaseAsset, QuoteAsset>, quantity: u64, account_cap: &custodian_v2::AccountCap, ctx: &mut tx_context::TxContext): coin::Coin<BaseAsset>
-
- - - -
-Implementation - - -

-public fun withdraw_base<BaseAsset, QuoteAsset>(
-    pool: &mut Pool<BaseAsset, QuoteAsset>,
-    quantity: u64,
-    account_cap: &AccountCap,
-    ctx: &mut TxContext
-): Coin<BaseAsset> \{
-    assert!(quantity > 0, EInvalidQuantity);
-    event::emit(WithdrawAsset<BaseAsset>\{
-        pool_id: *object::uid_as_inner(&pool.id),
-        quantity,
-        owner: account_owner(account_cap)
-    });
-    custodian::withdraw_asset(&mut pool.base_custodian, quantity, account_cap, ctx)
-}
-
- - - -
- - - -## Function `withdraw_quote` - - - -

-public fun withdraw_quote<BaseAsset, QuoteAsset>(pool: &mut clob_v2::Pool<BaseAsset, QuoteAsset>, quantity: u64, account_cap: &custodian_v2::AccountCap, ctx: &mut tx_context::TxContext): coin::Coin<QuoteAsset>
-
- - - -
-Implementation - - -

-public fun withdraw_quote<BaseAsset, QuoteAsset>(
-    pool: &mut Pool<BaseAsset, QuoteAsset>,
-    quantity: u64,
-    account_cap: &AccountCap,
-    ctx: &mut TxContext
-): Coin<QuoteAsset> \{
-    assert!(quantity > 0, EInvalidQuantity);
-    event::emit(WithdrawAsset<QuoteAsset>\{
-        pool_id: *object::uid_as_inner(&pool.id),
-        quantity,
-        owner: account_owner(account_cap)
-    });
-    custodian::withdraw_asset(&mut pool.quote_custodian, quantity, account_cap, ctx)
-}
-
- - - -
- - - -## Function `swap_exact_base_for_quote` - - - -

-public fun swap_exact_base_for_quote<BaseAsset, QuoteAsset>(pool: &mut clob_v2::Pool<BaseAsset, QuoteAsset>, client_order_id: u64, account_cap: &custodian_v2::AccountCap, quantity: u64, base_coin: coin::Coin<BaseAsset>, quote_coin: coin::Coin<QuoteAsset>, clock: &clock::Clock, ctx: &mut tx_context::TxContext): (coin::Coin<BaseAsset>, coin::Coin<QuoteAsset>, u64)
-
- - - -
-Implementation - - -

-public fun swap_exact_base_for_quote<BaseAsset, QuoteAsset>(
-    pool: &mut Pool<BaseAsset, QuoteAsset>,
-    client_order_id: u64,
-    account_cap: &AccountCap,
-    quantity: u64,
-    base_coin: Coin<BaseAsset>,
-    quote_coin: Coin<QuoteAsset>,
-    clock: &Clock,
-    ctx: &mut TxContext,
-): (Coin<BaseAsset>, Coin<QuoteAsset>, u64) \{
-    assert!(quantity > 0, EInvalidQuantity);
-    assert!(coin::value(&base_coin) >= quantity, EInsufficientBaseCoin);
-    let original_val = coin::value("e_coin);
-    let (ret_base_coin, ret_quote_coin) = place_market_order(
-        pool,
-        account_cap,
-        client_order_id,
-        quantity,
-        false,
-        base_coin,
-        quote_coin,
-        clock,
-        ctx
-    );
-    let ret_val = coin::value(&ret_quote_coin);
-    (ret_base_coin, ret_quote_coin, ret_val - original_val)
-}
-
- - - -
- - - -## Function `swap_exact_base_for_quote_with_metadata` - - - -

-public fun swap_exact_base_for_quote_with_metadata<BaseAsset, QuoteAsset>(pool: &mut clob_v2::Pool<BaseAsset, QuoteAsset>, client_order_id: u64, account_cap: &custodian_v2::AccountCap, quantity: u64, base_coin: coin::Coin<BaseAsset>, quote_coin: coin::Coin<QuoteAsset>, clock: &clock::Clock, ctx: &mut tx_context::TxContext): (coin::Coin<BaseAsset>, coin::Coin<QuoteAsset>, u64, vector<clob_v2::MatchedOrderMetadata<BaseAsset, QuoteAsset>>)
-
- - - -
-Implementation - - -

-public fun swap_exact_base_for_quote_with_metadata<BaseAsset, QuoteAsset>(
-    pool: &mut Pool<BaseAsset, QuoteAsset>,
-    client_order_id: u64,
-    account_cap: &AccountCap,
-    quantity: u64,
-    base_coin: Coin<BaseAsset>,
-    quote_coin: Coin<QuoteAsset>,
-    clock: &Clock,
-    ctx: &mut TxContext,
-): (Coin<BaseAsset>, Coin<QuoteAsset>, u64, vector<MatchedOrderMetadata<BaseAsset, QuoteAsset>>) \{
-    let original_val = coin::value("e_coin);
-    let (ret_base_coin, ret_quote_coin, mut matched_order_metadata) = place_market_order_int(
-        pool,
-        account_cap,
-        client_order_id,
-        quantity,
-        false,
-        base_coin,
-        quote_coin,
-        clock,
-        true, // return metadata
-        ctx
-    );
-    let ret_val = coin::value(&ret_quote_coin);
-    (ret_base_coin, ret_quote_coin, ret_val - original_val, option::extract(&mut matched_order_metadata))
-}
-
- - - -
- - - -## Function `swap_exact_quote_for_base` - - - -

-public fun swap_exact_quote_for_base<BaseAsset, QuoteAsset>(pool: &mut clob_v2::Pool<BaseAsset, QuoteAsset>, client_order_id: u64, account_cap: &custodian_v2::AccountCap, quantity: u64, clock: &clock::Clock, quote_coin: coin::Coin<QuoteAsset>, ctx: &mut tx_context::TxContext): (coin::Coin<BaseAsset>, coin::Coin<QuoteAsset>, u64)
-
- - - -
-Implementation - - -

-public fun swap_exact_quote_for_base<BaseAsset, QuoteAsset>(
-    pool: &mut Pool<BaseAsset, QuoteAsset>,
-    client_order_id: u64,
-    account_cap: &AccountCap,
-    quantity: u64,
-    clock: &Clock,
-    quote_coin: Coin<QuoteAsset>,
-    ctx: &mut TxContext,
-): (Coin<BaseAsset>, Coin<QuoteAsset>, u64) \{
-    assert!(quantity > 0, EInvalidQuantity);
-    assert!(coin::value("e_coin) >= quantity, EInsufficientQuoteCoin);
-    let (base_asset_balance, quote_asset_balance, _matched_order_metadata) = match_bid_with_quote_quantity(
-        pool,
-        account_cap,
-        client_order_id,
-        quantity,
-        MAX_PRICE,
-        clock::timestamp_ms(clock),
-        coin::into_balance(quote_coin),
-        false // don't return metadata
-    );
-    let val = balance::value(&base_asset_balance);
-    (coin::from_balance(base_asset_balance, ctx), coin::from_balance(quote_asset_balance, ctx), val)
-}
-
- - - -
- - - -## Function `swap_exact_quote_for_base_with_metadata` - - - -

-public fun swap_exact_quote_for_base_with_metadata<BaseAsset, QuoteAsset>(pool: &mut clob_v2::Pool<BaseAsset, QuoteAsset>, client_order_id: u64, account_cap: &custodian_v2::AccountCap, quantity: u64, clock: &clock::Clock, quote_coin: coin::Coin<QuoteAsset>, ctx: &mut tx_context::TxContext): (coin::Coin<BaseAsset>, coin::Coin<QuoteAsset>, u64, vector<clob_v2::MatchedOrderMetadata<BaseAsset, QuoteAsset>>)
-
- - - -
-Implementation - - -

-public fun swap_exact_quote_for_base_with_metadata<BaseAsset, QuoteAsset>(
-    pool: &mut Pool<BaseAsset, QuoteAsset>,
-    client_order_id: u64,
-    account_cap: &AccountCap,
-    quantity: u64,
-    clock: &Clock,
-    quote_coin: Coin<QuoteAsset>,
-    ctx: &mut TxContext,
-): (Coin<BaseAsset>, Coin<QuoteAsset>, u64, vector<MatchedOrderMetadata<BaseAsset, QuoteAsset>>) \{
-    assert!(quantity > 0, EInvalidQuantity);
-    assert!(coin::value("e_coin) >= quantity, EInsufficientQuoteCoin);
-    let (base_asset_balance, quote_asset_balance, mut matched_order_metadata) = match_bid_with_quote_quantity(
-        pool,
-        account_cap,
-        client_order_id,
-        quantity,
-        MAX_PRICE,
-        clock::timestamp_ms(clock),
-        coin::into_balance(quote_coin),
-        true // return metadata
-    );
-    let val = balance::value(&base_asset_balance);
-    (coin::from_balance(base_asset_balance, ctx), coin::from_balance(quote_asset_balance, ctx), val, option::extract(&mut matched_order_metadata))
-}
-
- - - -
- - - -## Function `match_bid_with_quote_quantity` - - - -

-fun match_bid_with_quote_quantity<BaseAsset, QuoteAsset>(pool: &mut clob_v2::Pool<BaseAsset, QuoteAsset>, account_cap: &custodian_v2::AccountCap, client_order_id: u64, quantity: u64, price_limit: u64, current_timestamp: u64, quote_balance: balance::Balance<QuoteAsset>, compute_metadata: bool): (balance::Balance<BaseAsset>, balance::Balance<QuoteAsset>, option::Option<vector<clob_v2::MatchedOrderMetadata<BaseAsset, QuoteAsset>>>)
-
- - - -
-Implementation - - -

-fun match_bid_with_quote_quantity<BaseAsset, QuoteAsset>(
-    pool: &mut Pool<BaseAsset, QuoteAsset>,
-    account_cap: &AccountCap,
-    client_order_id: u64,
-    quantity: u64,
-    price_limit: u64,
-    current_timestamp: u64,
-    quote_balance: Balance<QuoteAsset>,
-    compute_metadata: bool,
-): (Balance<BaseAsset>, Balance<QuoteAsset>, Option<vector<MatchedOrderMetadata<BaseAsset, QuoteAsset>>>) \{
-    // Base balance received by taker, taking into account of taker commission.
-    // Need to individually keep track of the remaining base quantity to be filled to avoid infinite loop.
-    let pool_id = *object::uid_as_inner(&pool.id);
-    let mut taker_quote_quantity_remaining = quantity;
-    let mut base_balance_filled = balance::zero<BaseAsset>();
-    let mut quote_balance_left = quote_balance;
-    let all_open_orders = &mut pool.asks;
-    let mut matched_order_metadata = vector::empty<MatchedOrderMetadata<BaseAsset, QuoteAsset>>();
-    if (critbit::is_empty(all_open_orders)) \{
-        return (base_balance_filled, quote_balance_left, option::none())
-    };
-    let (mut tick_price, mut tick_index) = min_leaf(all_open_orders);
-    let mut terminate_loop = false;
-    let mut canceled_order_events = vector[];
-
-    while (!is_empty<TickLevel>(all_open_orders) && tick_price <= price_limit) \{
-        let tick_level = borrow_mut_leaf_by_index(all_open_orders, tick_index);
-        let mut order_id = *option::borrow(linked_table::front(&tick_level.open_orders));
-
-        while (!linked_table::is_empty(&tick_level.open_orders)) \{
-            let maker_order = linked_table::borrow(&tick_level.open_orders, order_id);
-            let mut maker_base_quantity = maker_order.quantity;
-            let mut skip_order = false;
-
-            if (maker_order.expire_timestamp <= current_timestamp || account_owner(account_cap) == maker_order.owner) \{
-                skip_order = true;
-                custodian::unlock_balance(&mut pool.base_custodian, maker_order.owner, maker_order.quantity);
-                let canceled_order_event = AllOrdersCanceledComponent<BaseAsset, QuoteAsset> \{
-                    client_order_id: maker_order.client_order_id,
-                    order_id: maker_order.order_id,
-                    is_bid: maker_order.is_bid,
-                    owner: maker_order.owner,
-                    original_quantity: maker_order.original_quantity,
-                    base_asset_quantity_canceled: maker_order.quantity,
-                    price: maker_order.price
-                };
-
-                vector::push_back(&mut canceled_order_events, canceled_order_event);
-
-            } else \{
-                // Calculate how much quote asset (maker_quote_quantity) is required, including the commission, to fill the maker order.
-                let maker_quote_quantity_without_commission = clob_math::mul(
-                    maker_base_quantity,
-                    maker_order.price
-                );
-                let (is_round_down, mut taker_commission)  = clob_math::unsafe_mul_round(
-                    maker_quote_quantity_without_commission,
-                    pool.taker_fee_rate
-                );
-                if (is_round_down)  taker_commission = taker_commission + 1;
-
-                let maker_quote_quantity = maker_quote_quantity_without_commission + taker_commission;
-
-                // Total base quantity filled.
-                let mut filled_base_quantity: u64;
-                // Total quote quantity filled, excluding commission and rebate.
-                let mut filled_quote_quantity: u64;
-                // Total quote quantity paid by taker.
-                // filled_quote_quantity_without_commission * (FLOAT_SCALING + taker_fee_rate) = filled_quote_quantity
-                let mut filled_quote_quantity_without_commission: u64;
-                if (taker_quote_quantity_remaining > maker_quote_quantity) \{
-                    filled_quote_quantity = maker_quote_quantity;
-                    filled_quote_quantity_without_commission = maker_quote_quantity_without_commission;
-                    filled_base_quantity = maker_base_quantity;
-                } else \{
-                    terminate_loop = true;
-                    // if not enough quote quantity to pay for taker commission, then no quantity will be filled
-                    filled_quote_quantity_without_commission = clob_math::unsafe_div(
-                        taker_quote_quantity_remaining,
-                        FLOAT_SCALING + pool.taker_fee_rate
-                    );
-                    // filled_base_quantity = 0 is permitted since filled_quote_quantity_without_commission can be 0
-                    filled_base_quantity = clob_math::unsafe_div(
-                        filled_quote_quantity_without_commission,
-                        maker_order.price
-                    );
-                    let filled_base_lot = filled_base_quantity / pool.lot_size;
-                    filled_base_quantity = filled_base_lot * pool.lot_size;
-                    // filled_quote_quantity_without_commission = 0 is permitted here since filled_base_quantity could be 0
-                    filled_quote_quantity_without_commission = clob_math::unsafe_mul(
-                        filled_base_quantity,
-                        maker_order.price
-                    );
-                    // if taker_commission = 0 due to underflow, round it up to 1
-                    let (round_down, mut taker_commission) = clob_math::unsafe_mul_round(
-                        filled_quote_quantity_without_commission,
-                        pool.taker_fee_rate
-                    );
-                    if (round_down) \{
-                        taker_commission = taker_commission + 1;
-                    };
-                    filled_quote_quantity = filled_quote_quantity_without_commission + taker_commission;
-                };
-                // if maker_rebate = 0 due to underflow, maker will not receive a rebate
-                let maker_rebate = clob_math::unsafe_mul(
-                    filled_quote_quantity_without_commission,
-                    pool.maker_rebate_rate
-                );
-                maker_base_quantity = maker_base_quantity - filled_base_quantity;
-
-                // maker in ask side, decrease maker's locked base asset, increase maker's available quote asset
-                taker_quote_quantity_remaining = taker_quote_quantity_remaining - filled_quote_quantity;
-                let locked_base_balance = custodian::decrease_user_locked_balance<BaseAsset>(
-                    &mut pool.base_custodian,
-                    maker_order.owner,
-                    filled_base_quantity
-                );
-
-                let mut quote_balance_filled = balance::split(
-                    &mut quote_balance_left,
-                    filled_quote_quantity,
-                );
-                // Send quote asset including rebate to maker.
-                custodian::increase_user_available_balance<QuoteAsset>(
-                    &mut pool.quote_custodian,
-                    maker_order.owner,
-                    balance::split(
-                        &mut quote_balance_filled,
-                        maker_rebate + filled_quote_quantity_without_commission,
-                    ),
-                );
-                // Send remaining of commission - rebate to the protocol.
-                // commission - rebate = filled_quote_quantity_without_commission - filled_quote_quantity - maker_rebate
-                balance::join(&mut pool.quote_asset_trading_fees, quote_balance_filled);
-                balance::join(&mut base_balance_filled, locked_base_balance);
-
-                emit_order_filled<BaseAsset, QuoteAsset>(
-                    *object::uid_as_inner(&pool.id),
-                    client_order_id,
-                    account_owner(account_cap),
-                    maker_order,
-                    filled_base_quantity,
-                    // taker_commission = filled_quote_quantity - filled_quote_quantity_without_commission
-                    // This guarantees that the subtraction will not underflow
-                    filled_quote_quantity - filled_quote_quantity_without_commission,
-                    maker_rebate
-                );
-                if(compute_metadata) \{
-                    vector::push_back(
-                        &mut matched_order_metadata,
-                        matched_order_metadata(
-                            *object::uid_as_inner(&pool.id),
-                            account_owner(account_cap),
-                            maker_order,
-                            filled_base_quantity,
-                            // taker_commission = filled_quote_quantity - filled_quote_quantity_without_commission
-                            // This guarantees that the subtraction will not underflow
-                            filled_quote_quantity - filled_quote_quantity_without_commission,
-                            maker_rebate
-                        )
-                    );
-                };
-            };
-
-            if (skip_order || maker_base_quantity == 0) \{
-                // Remove the maker order.
-                let old_order_id = order_id;
-                let maybe_order_id = linked_table::next(&tick_level.open_orders, order_id);
-                if (!option::is_none(maybe_order_id)) \{
-                    order_id = *option::borrow(maybe_order_id);
-                };
-                let usr_open_order_ids = table::borrow_mut(&mut pool.usr_open_orders, maker_order.owner);
-                linked_table::remove(usr_open_order_ids, old_order_id);
-                linked_table::remove(&mut tick_level.open_orders, old_order_id);
-            } else \{
-                // Update the maker order.
-                let maker_order_mut = linked_table::borrow_mut(
-                    &mut tick_level.open_orders,
-                    order_id);
-                maker_order_mut.quantity = maker_base_quantity;
-            };
-            if (terminate_loop) \{
-                break
-            };
-        };
-        if (linked_table::is_empty(&tick_level.open_orders)) \{
-            (tick_price, _) = next_leaf(all_open_orders, tick_price);
-            destroy_empty_level(remove_leaf_by_index(all_open_orders, tick_index));
-            (_, tick_index) = find_leaf(all_open_orders, tick_price);
-        };
-        if (terminate_loop) \{
-            break
-        };
-    };
-
-    if (!vector::is_empty(&canceled_order_events)) \{
-        event::emit(AllOrdersCanceled<BaseAsset, QuoteAsset> \{
-            pool_id,
-            orders_canceled: canceled_order_events,
-        });
-    };
-
-    return (base_balance_filled, quote_balance_left, if(compute_metadata) option::some(matched_order_metadata) else option::none())
-}
-
- - - -
- - - -## Function `match_bid` - - - -

-fun match_bid<BaseAsset, QuoteAsset>(pool: &mut clob_v2::Pool<BaseAsset, QuoteAsset>, account_cap: &custodian_v2::AccountCap, client_order_id: u64, quantity: u64, price_limit: u64, current_timestamp: u64, quote_balance: balance::Balance<QuoteAsset>, compute_metadata: bool): (balance::Balance<BaseAsset>, balance::Balance<QuoteAsset>, option::Option<vector<clob_v2::MatchedOrderMetadata<BaseAsset, QuoteAsset>>>)
-
- - - -
-Implementation - - -

-fun match_bid<BaseAsset, QuoteAsset>(
-    pool: &mut Pool<BaseAsset, QuoteAsset>,
-    account_cap: &AccountCap,
-    client_order_id: u64,
-    quantity: u64,
-    price_limit: u64,
-    current_timestamp: u64,
-    quote_balance: Balance<QuoteAsset>,
-    compute_metadata: bool,
-): (Balance<BaseAsset>, Balance<QuoteAsset>, Option<vector<MatchedOrderMetadata<BaseAsset, QuoteAsset>>>) \{
-    let pool_id = *object::uid_as_inner(&pool.id);
-    // Base balance received by taker.
-    // Need to individually keep track of the remaining base quantity to be filled to avoid infinite loop.
-    let mut taker_base_quantity_remaining = quantity;
-    let mut base_balance_filled = balance::zero<BaseAsset>();
-    let mut quote_balance_left = quote_balance;
-    let all_open_orders = &mut pool.asks;
-    let mut matched_order_metadata = vector::empty<MatchedOrderMetadata<BaseAsset, QuoteAsset>>();
-    if (critbit::is_empty(all_open_orders)) \{
-        return (base_balance_filled, quote_balance_left, option::none())
-    };
-    let (mut tick_price, mut tick_index) = min_leaf(all_open_orders);
-    let mut canceled_order_events = vector[];
-
-    while (!is_empty<TickLevel>(all_open_orders) && tick_price <= price_limit) \{
-        let tick_level = borrow_mut_leaf_by_index(all_open_orders, tick_index);
-        let mut order_id = *option::borrow(linked_table::front(&tick_level.open_orders));
-
-        while (!linked_table::is_empty(&tick_level.open_orders)) \{
-            let maker_order = linked_table::borrow(&tick_level.open_orders, order_id);
-            let mut maker_base_quantity = maker_order.quantity;
-            let mut skip_order = false;
-
-            if (maker_order.expire_timestamp <= current_timestamp || account_owner(account_cap) == maker_order.owner) \{
-                skip_order = true;
-                custodian::unlock_balance(&mut pool.base_custodian, maker_order.owner, maker_order.quantity);
-                let canceled_order_event = AllOrdersCanceledComponent<BaseAsset, QuoteAsset> \{
-                    client_order_id: maker_order.client_order_id,
-                    order_id: maker_order.order_id,
-                    is_bid: maker_order.is_bid,
-                    owner: maker_order.owner,
-                    original_quantity: maker_order.original_quantity,
-                    base_asset_quantity_canceled: maker_order.quantity,
-                    price: maker_order.price
-                };
-                vector::push_back(&mut canceled_order_events, canceled_order_event);
-
-            } else \{
-                let filled_base_quantity =
-                    if (taker_base_quantity_remaining > maker_base_quantity) \{ maker_base_quantity }
-                    else \{ taker_base_quantity_remaining };
-                // Note that if a user creates a pool that allows orders that are too small, this will fail since we cannot have a filled
-                // quote quantity of 0.
-                let filled_quote_quantity = clob_math::mul(filled_base_quantity, maker_order.price);
-
-                // if maker_rebate = 0 due to underflow, maker will not receive a rebate
-                let maker_rebate = clob_math::unsafe_mul(filled_quote_quantity, pool.maker_rebate_rate);
-                // if taker_commission = 0 due to underflow, round it up to 1
-                let (is_round_down, mut taker_commission) = clob_math::unsafe_mul_round(
-                    filled_quote_quantity,
-                    pool.taker_fee_rate
-                );
-                if (is_round_down) taker_commission = taker_commission + 1;
-
-                maker_base_quantity = maker_base_quantity - filled_base_quantity;
-
-                // maker in ask side, decrease maker's locked base asset, increase maker's available quote asset
-                taker_base_quantity_remaining = taker_base_quantity_remaining - filled_base_quantity;
-                let locked_base_balance = custodian::decrease_user_locked_balance<BaseAsset>(
-                    &mut pool.base_custodian,
-                    maker_order.owner,
-                    filled_base_quantity
-                );
-                let mut taker_commission_balance = balance::split(
-                    &mut quote_balance_left,
-                    taker_commission,
-                );
-                custodian::increase_user_available_balance<QuoteAsset>(
-                    &mut pool.quote_custodian,
-                    maker_order.owner,
-                    balance::split(
-                        &mut taker_commission_balance,
-                        maker_rebate,
-                    ),
-                );
-                balance::join(&mut pool.quote_asset_trading_fees, taker_commission_balance);
-                balance::join(&mut base_balance_filled, locked_base_balance);
-
-                custodian::increase_user_available_balance<QuoteAsset>(
-                    &mut pool.quote_custodian,
-                    maker_order.owner,
-                    balance::split(
-                        &mut quote_balance_left,
-                        filled_quote_quantity,
-                    ),
-                );
-
-                emit_order_filled<BaseAsset, QuoteAsset>(
-                    *object::uid_as_inner(&pool.id),
-                    client_order_id,
-                    account_owner(account_cap),
-                    maker_order,
-                    filled_base_quantity,
-                    taker_commission,
-                    maker_rebate
-                );
-                if(compute_metadata)\{
-                    vector::push_back(
-                        &mut matched_order_metadata,
-                        matched_order_metadata(
-                            *object::uid_as_inner(&pool.id),
-                            account_owner(account_cap),
-                            maker_order,
-                            filled_base_quantity,
-                            taker_commission,
-                            maker_rebate
-                        )
-                    );
-                };
-            };
-
-            if (skip_order || maker_base_quantity == 0) \{
-                // Remove the maker order.
-                let old_order_id = order_id;
-                let maybe_order_id = linked_table::next(&tick_level.open_orders, order_id);
-                if (!option::is_none(maybe_order_id)) \{
-                    order_id = *option::borrow(maybe_order_id);
-                };
-                let usr_open_order_ids = table::borrow_mut(&mut pool.usr_open_orders, maker_order.owner);
-                linked_table::remove(usr_open_order_ids, old_order_id);
-                linked_table::remove(&mut tick_level.open_orders, old_order_id);
-            } else \{
-                // Update the maker order.
-                let maker_order_mut = linked_table::borrow_mut(
-                    &mut tick_level.open_orders,
-                    order_id);
-                maker_order_mut.quantity = maker_base_quantity;
-            };
-            if (taker_base_quantity_remaining == 0) \{
-                break
-            };
-        };
-        if (linked_table::is_empty(&tick_level.open_orders)) \{
-            (tick_price, _) = next_leaf(all_open_orders, tick_price);
-            destroy_empty_level(remove_leaf_by_index(all_open_orders, tick_index));
-            (_, tick_index) = find_leaf(all_open_orders, tick_price);
-        };
-        if (taker_base_quantity_remaining == 0) \{
-            break
-        };
-    };
-
-    if (!vector::is_empty(&canceled_order_events)) \{
-        event::emit(AllOrdersCanceled<BaseAsset, QuoteAsset> \{
-            pool_id,
-            orders_canceled: canceled_order_events,
-        });
-    };
-    return (base_balance_filled, quote_balance_left, if(compute_metadata) option::some(matched_order_metadata) else option::none())
-}
-
- - - -
- - - -## Function `match_ask` - - - -

-fun match_ask<BaseAsset, QuoteAsset>(pool: &mut clob_v2::Pool<BaseAsset, QuoteAsset>, account_cap: &custodian_v2::AccountCap, client_order_id: u64, price_limit: u64, current_timestamp: u64, base_balance: balance::Balance<BaseAsset>, compute_metadata: bool): (balance::Balance<BaseAsset>, balance::Balance<QuoteAsset>, option::Option<vector<clob_v2::MatchedOrderMetadata<BaseAsset, QuoteAsset>>>)
-
- - - -
-Implementation - - -

-fun match_ask<BaseAsset, QuoteAsset>(
-    pool: &mut Pool<BaseAsset, QuoteAsset>,
-    account_cap: &AccountCap,
-    client_order_id: u64,
-    price_limit: u64,
-    current_timestamp: u64,
-    base_balance: Balance<BaseAsset>,
-    compute_metadata: bool,
-): (Balance<BaseAsset>, Balance<QuoteAsset>, Option<vector<MatchedOrderMetadata<BaseAsset, QuoteAsset>>>) \{
-    let pool_id = *object::uid_as_inner(&pool.id);
-    let mut base_balance_left = base_balance;
-    // Base balance received by taker, taking into account of taker commission.
-    let mut quote_balance_filled = balance::zero<QuoteAsset>();
-    let all_open_orders = &mut pool.bids;
-    let mut matched_order_metadata = vector::empty<MatchedOrderMetadata<BaseAsset, QuoteAsset>>();
-    if (critbit::is_empty(all_open_orders)) \{
-        return (base_balance_left, quote_balance_filled, option::none())
-    };
-    let (mut tick_price, mut tick_index) = max_leaf(all_open_orders);
-    let mut canceled_order_events = vector[];
-    while (!is_empty<TickLevel>(all_open_orders) && tick_price >= price_limit) \{
-        let tick_level = borrow_mut_leaf_by_index(all_open_orders, tick_index);
-        let mut order_id = *option::borrow(linked_table::front(&tick_level.open_orders));
-        while (!linked_table::is_empty(&tick_level.open_orders)) \{
-            let maker_order = linked_table::borrow(&tick_level.open_orders, order_id);
-            let mut maker_base_quantity = maker_order.quantity;
-            let mut skip_order = false;
-
-            if (maker_order.expire_timestamp <= current_timestamp || account_owner(account_cap) == maker_order.owner) \{
-                skip_order = true;
-                let maker_quote_quantity = clob_math::mul(maker_order.quantity, maker_order.price);
-                custodian::unlock_balance(&mut pool.quote_custodian, maker_order.owner, maker_quote_quantity);
-                let canceled_order_event = AllOrdersCanceledComponent<BaseAsset, QuoteAsset> \{
-                    client_order_id: maker_order.client_order_id,
-                    order_id: maker_order.order_id,
-                    is_bid: maker_order.is_bid,
-                    owner: maker_order.owner,
-                    original_quantity: maker_order.original_quantity,
-                    base_asset_quantity_canceled: maker_order.quantity,
-                    price: maker_order.price
-                };
-                vector::push_back(&mut canceled_order_events, canceled_order_event);
-            } else \{
-                let taker_base_quantity_remaining = balance::value(&base_balance_left);
-                let filled_base_quantity =
-                    if (taker_base_quantity_remaining >= maker_base_quantity) \{ maker_base_quantity }
-                    else \{ taker_base_quantity_remaining };
-                // If a bit is rounded down, the pool will take this as a fee.
-                let (is_round_down, filled_quote_quantity) = clob_math::unsafe_mul_round(filled_base_quantity, maker_order.price);
-                if (is_round_down) \{
-                    let rounded_down_quantity = custodian::decrease_user_locked_balance<QuoteAsset>(
-                        &mut pool.quote_custodian,
-                        maker_order.owner,
-                        1
-                    );
-                    balance::join(&mut pool.quote_asset_trading_fees, rounded_down_quantity);
-                };
-
-                // if maker_rebate = 0 due to underflow, maker will not receive a rebate
-                let maker_rebate = clob_math::unsafe_mul(filled_quote_quantity, pool.maker_rebate_rate);
-                // if taker_commission = 0 due to underflow, round it up to 1
-                let (is_round_down, mut taker_commission) = clob_math::unsafe_mul_round(
-                    filled_quote_quantity,
-                    pool.taker_fee_rate
-                );
-                if (is_round_down) taker_commission = taker_commission + 1;
-
-                maker_base_quantity = maker_base_quantity - filled_base_quantity;
-                // maker in bid side, decrease maker's locked quote asset, increase maker's available base asset
-                let mut locked_quote_balance = custodian::decrease_user_locked_balance<QuoteAsset>(
-                    &mut pool.quote_custodian,
-                    maker_order.owner,
-                    filled_quote_quantity
-                );
-                let mut taker_commission_balance = balance::split(
-                    &mut locked_quote_balance,
-                    taker_commission,
-                );
-                custodian::increase_user_available_balance<QuoteAsset>(
-                    &mut pool.quote_custodian,
-                    maker_order.owner,
-                    balance::split(
-                        &mut taker_commission_balance,
-                        maker_rebate,
-                    ),
-                );
-                balance::join(&mut pool.quote_asset_trading_fees, taker_commission_balance);
-                balance::join(&mut quote_balance_filled, locked_quote_balance);
-
-                custodian::increase_user_available_balance<BaseAsset>(
-                    &mut pool.base_custodian,
-                    maker_order.owner,
-                    balance::split(
-                        &mut base_balance_left,
-                        filled_base_quantity,
-                    ),
-                );
-                emit_order_filled<BaseAsset, QuoteAsset>(
-                    *object::uid_as_inner(&pool.id),
-                    client_order_id,
-                    account_owner(account_cap),
-                    maker_order,
-                    filled_base_quantity,
-                    taker_commission,
-                    maker_rebate
-                );
-                if(compute_metadata) \{
-                    vector::push_back(
-                        &mut matched_order_metadata,
-                        matched_order_metadata(
-                            *object::uid_as_inner(&pool.id),
-                            account_owner(account_cap),
-                            maker_order,
-                            filled_base_quantity,
-                            taker_commission,
-                            maker_rebate
-                        )
-                    );
-                }
-            };
-
-            if (skip_order || maker_base_quantity == 0) \{
-                // Remove the maker order.
-                let old_order_id = order_id;
-                let maybe_order_id = linked_table::next(&tick_level.open_orders, order_id);
-                if (!option::is_none(maybe_order_id)) \{
-                    order_id = *option::borrow(maybe_order_id);
-                };
-                let usr_open_order_ids = table::borrow_mut(&mut pool.usr_open_orders, maker_order.owner);
-                linked_table::remove(usr_open_order_ids, old_order_id);
-                linked_table::remove(&mut tick_level.open_orders, old_order_id);
-            } else \{
-                // Update the maker order.
-                let maker_order_mut = linked_table::borrow_mut(
-                    &mut tick_level.open_orders,
-                    order_id);
-                maker_order_mut.quantity = maker_base_quantity;
-            };
-            if (balance::value(&base_balance_left) == 0) \{
-                break
-            };
-        };
-        if (linked_table::is_empty(&tick_level.open_orders)) \{
-            (tick_price, _) = previous_leaf(all_open_orders, tick_price);
-            destroy_empty_level(remove_leaf_by_index(all_open_orders, tick_index));
-            (_, tick_index) = find_leaf(all_open_orders, tick_price);
-        };
-        if (balance::value(&base_balance_left) == 0) \{
-            break
-        };
-    };
-
-    if (!vector::is_empty(&canceled_order_events)) \{
-        event::emit(AllOrdersCanceled<BaseAsset, QuoteAsset> \{
-            pool_id,
-            orders_canceled: canceled_order_events,
-        });
-    };
-
-    return (base_balance_left, quote_balance_filled, if(compute_metadata) option::some(matched_order_metadata) else option::none())
-}
-
- - - -
- - - -## Function `place_market_order` - -Place a market order to the order book. - - -

-public fun place_market_order<BaseAsset, QuoteAsset>(pool: &mut clob_v2::Pool<BaseAsset, QuoteAsset>, account_cap: &custodian_v2::AccountCap, client_order_id: u64, quantity: u64, is_bid: bool, base_coin: coin::Coin<BaseAsset>, quote_coin: coin::Coin<QuoteAsset>, clock: &clock::Clock, ctx: &mut tx_context::TxContext): (coin::Coin<BaseAsset>, coin::Coin<QuoteAsset>)
-
- - - -
-Implementation - - -

-public fun place_market_order<BaseAsset, QuoteAsset>(
-    pool: &mut Pool<BaseAsset, QuoteAsset>,
-    account_cap: &AccountCap,
-    client_order_id: u64,
-    quantity: u64,
-    is_bid: bool,
-    base_coin: Coin<BaseAsset>,
-    quote_coin: Coin<QuoteAsset>,
-    clock: &Clock,
-    ctx: &mut TxContext,
-): (Coin<BaseAsset>, Coin<QuoteAsset>) \{
-    let (base_coin, quote_coin, _metadata) = place_market_order_int(
-        pool,
-        account_cap,
-        client_order_id,
-        quantity,
-        is_bid,
-        base_coin,
-        quote_coin,
-        clock,
-        false, // don't return metadata
-        ctx
-    );
-    (base_coin, quote_coin)
-}
-
- - - -
- - - -## Function `place_market_order_with_metadata` - - - -

-public fun place_market_order_with_metadata<BaseAsset, QuoteAsset>(pool: &mut clob_v2::Pool<BaseAsset, QuoteAsset>, account_cap: &custodian_v2::AccountCap, client_order_id: u64, quantity: u64, is_bid: bool, base_coin: coin::Coin<BaseAsset>, quote_coin: coin::Coin<QuoteAsset>, clock: &clock::Clock, ctx: &mut tx_context::TxContext): (coin::Coin<BaseAsset>, coin::Coin<QuoteAsset>, vector<clob_v2::MatchedOrderMetadata<BaseAsset, QuoteAsset>>)
-
- - - -
-Implementation - - -

-public fun place_market_order_with_metadata<BaseAsset, QuoteAsset>(
-    pool: &mut Pool<BaseAsset, QuoteAsset>,
-    account_cap: &AccountCap,
-    client_order_id: u64,
-    quantity: u64,
-    is_bid: bool,
-    base_coin: Coin<BaseAsset>,
-    quote_coin: Coin<QuoteAsset>,
-    clock: &Clock,
-    ctx: &mut TxContext,
-): (Coin<BaseAsset>, Coin<QuoteAsset>, vector<MatchedOrderMetadata<BaseAsset, QuoteAsset>>) \{
-    let (base_coin, quote_coin, mut metadata) = place_market_order_int(
-        pool,
-        account_cap,
-        client_order_id,
-        quantity,
-        is_bid,
-        base_coin,
-        quote_coin,
-        clock,
-        true, // return metadata
-        ctx
-    );
-    (base_coin, quote_coin, option::extract(&mut metadata))
-}
-
- - - -
- - - -## Function `place_market_order_int` - -Place a market order to the order book. - - -

-fun place_market_order_int<BaseAsset, QuoteAsset>(pool: &mut clob_v2::Pool<BaseAsset, QuoteAsset>, account_cap: &custodian_v2::AccountCap, client_order_id: u64, quantity: u64, is_bid: bool, base_coin: coin::Coin<BaseAsset>, quote_coin: coin::Coin<QuoteAsset>, clock: &clock::Clock, compute_metadata: bool, ctx: &mut tx_context::TxContext): (coin::Coin<BaseAsset>, coin::Coin<QuoteAsset>, option::Option<vector<clob_v2::MatchedOrderMetadata<BaseAsset, QuoteAsset>>>)
-
- - - -
-Implementation - - -

-fun place_market_order_int<BaseAsset, QuoteAsset>(
-    pool: &mut Pool<BaseAsset, QuoteAsset>,
-    account_cap: &AccountCap,
-    client_order_id: u64,
-    quantity: u64,
-    is_bid: bool,
-    mut base_coin: Coin<BaseAsset>,
-    mut quote_coin: Coin<QuoteAsset>,
-    clock: &Clock,
-    compute_metadata: bool,
-    ctx: &mut TxContext,
-): (Coin<BaseAsset>, Coin<QuoteAsset>, Option<vector<MatchedOrderMetadata<BaseAsset, QuoteAsset>>>) \{
-    // If market bid order, match against the open ask orders. Otherwise, match against the open bid orders.
-    // Take market bid order for example.
-    // We first retrieve the PriceLevel with the lowest price by calling min_leaf on the asks Critbit Tree.
-    // We then match the market order by iterating through open orders on that price level in ascending order of the order id.
-    // Open orders that are being filled are removed from the order book.
-    // We stop the iteration until all quantities are filled.
-    // If the total quantity of open orders at the lowest price level is not large enough to fully fill the market order,
-    // we move on to the next price level by calling next_leaf on the asks Critbit Tree and repeat the same procedure.
-    // Continue iterating over the price levels in ascending order until the market order is completely filled.
-    // If their market order cannot be completely filled even after consuming all the open ask orders,
-    // the unfilled quantity will be cancelled.
-    // Market ask order follows similar procedure.
-    // The difference is that market ask order is matched against the open bid orders.
-    // We start with the bid PriceLevel with the highest price by calling max_leaf on the bids Critbit Tree.
-    // The inner loop for iterating over the open orders in ascending orders of order id is the same as above.
-    // Then iterate over the price levels in descending order until the market order is completely filled.
-    assert!(quantity % pool.lot_size == 0, EInvalidQuantity);
-    assert!(quantity != 0, EInvalidQuantity);
-    let metadata;
-    if (is_bid) \{
-        let (base_balance_filled, quote_balance_left, matched_order_metadata) = match_bid(
-            pool,
-            account_cap,
-            client_order_id,
-            quantity,
-            MAX_PRICE,
-            clock::timestamp_ms(clock),
-            coin::into_balance(quote_coin),
-            compute_metadata
-        );
-        join(
-            &mut base_coin,
-            coin::from_balance(base_balance_filled, ctx),
-        );
-        quote_coin = coin::from_balance(quote_balance_left, ctx);
-        metadata = matched_order_metadata;
-    } else \{
-        assert!(quantity <= coin::value(&base_coin), EInsufficientBaseCoin);
-        let base_coin_to_sell = coin::split(&mut base_coin, quantity, ctx);
-        let (base_balance_left, quote_balance_filled, matched_order_metadata) = match_ask(
-            pool,
-            account_cap,
-            client_order_id,
-            MIN_PRICE,
-            clock::timestamp_ms(clock),
-            coin::into_balance(base_coin_to_sell),
-            compute_metadata
-        );
-        join(
-            &mut base_coin,
-            coin::from_balance(base_balance_left, ctx));
-        join(
-            &mut quote_coin,
-            coin::from_balance(quote_balance_filled, ctx),
-        );
-        metadata = matched_order_metadata;
-    };
-    (base_coin, quote_coin, metadata)
-}
-
- - - -
- - - -## Function `inject_limit_order` - -Injects a maker order to the order book. -Returns the order id. - - -

-fun inject_limit_order<BaseAsset, QuoteAsset>(pool: &mut clob_v2::Pool<BaseAsset, QuoteAsset>, client_order_id: u64, price: u64, original_quantity: u64, quantity: u64, is_bid: bool, self_matching_prevention: u8, expire_timestamp: u64, account_cap: &custodian_v2::AccountCap, ctx: &mut tx_context::TxContext): u64
-
- - - -
-Implementation - - -

-fun inject_limit_order<BaseAsset, QuoteAsset>(
-    pool: &mut Pool<BaseAsset, QuoteAsset>,
-    client_order_id: u64,
-    price: u64,
-    original_quantity: u64,
-    quantity: u64,
-    is_bid: bool,
-    self_matching_prevention: u8,
-    expire_timestamp: u64,
-    account_cap: &AccountCap,
-    ctx: &mut TxContext
-): u64 \{
-    let owner = account_owner(account_cap);
-    let order_id: u64;
-    let open_orders: &mut CritbitTree<TickLevel>;
-    if (is_bid) \{
-        let quote_quantity = clob_math::mul(quantity, price);
-        custodian::lock_balance<QuoteAsset>(&mut pool.quote_custodian, account_cap, quote_quantity);
-        order_id = pool.next_bid_order_id;
-        pool.next_bid_order_id = pool.next_bid_order_id + 1;
-        open_orders = &mut pool.bids;
-    } else \{
-        custodian::lock_balance<BaseAsset>(&mut pool.base_custodian, account_cap, quantity);
-        order_id = pool.next_ask_order_id;
-        pool.next_ask_order_id = pool.next_ask_order_id + 1;
-        open_orders = &mut pool.asks;
-    };
-    let order = Order \{
-        order_id,
-        client_order_id,
-        price,
-        original_quantity,
-        quantity,
-        is_bid,
-        owner,
-        expire_timestamp,
-        self_matching_prevention
-    };
-    let (tick_exists, mut tick_index) = find_leaf(open_orders, price);
-    if (!tick_exists) \{
-        tick_index = insert_leaf(
-            open_orders,
-            price,
-            TickLevel \{
-                price,
-                open_orders: linked_table::new(ctx),
-            });
-    };
-
-    let tick_level = borrow_mut_leaf_by_index(open_orders, tick_index);
-    linked_table::push_back(&mut tick_level.open_orders, order_id, order);
-    event::emit(OrderPlaced<BaseAsset, QuoteAsset> \{
-        pool_id: *object::uid_as_inner(&pool.id),
-        order_id,
-        client_order_id,
-        is_bid,
-        owner,
-        original_quantity,
-        base_asset_quantity_placed: quantity,
-        price,
-        expire_timestamp
-    });
-    if (!contains(&pool.usr_open_orders, owner)) \{
-        add(&mut pool.usr_open_orders, owner, linked_table::new(ctx));
-    };
-    linked_table::push_back(borrow_mut(&mut pool.usr_open_orders, owner), order_id, price);
-
-    return order_id
-}
-
- - - -
- - - -## Function `place_limit_order` - -Place a limit order to the order book. -Returns (base quantity filled, quote quantity filled, whether a maker order is being placed, order id of the maker order). -When the limit order is not successfully placed, we return false to indicate that and also returns a meaningless order_id 0. -When the limit order is successfully placed, we return true to indicate that and also the corresponding order_id. -So please check that boolean value first before using the order id. - - -

-public fun place_limit_order<BaseAsset, QuoteAsset>(pool: &mut clob_v2::Pool<BaseAsset, QuoteAsset>, client_order_id: u64, price: u64, quantity: u64, self_matching_prevention: u8, is_bid: bool, expire_timestamp: u64, restriction: u8, clock: &clock::Clock, account_cap: &custodian_v2::AccountCap, ctx: &mut tx_context::TxContext): (u64, u64, bool, u64)
-
- - - -
-Implementation - - -

-public fun place_limit_order<BaseAsset, QuoteAsset>(
-    pool: &mut Pool<BaseAsset, QuoteAsset>,
-    client_order_id: u64,
-    price: u64,
-    quantity: u64,
-    self_matching_prevention: u8,
-    is_bid: bool,
-    expire_timestamp: u64, // Expiration timestamp in ms in absolute value inclusive.
-    restriction: u8,
-    clock: &Clock,
-    account_cap: &AccountCap,
-    ctx: &mut TxContext
-): (u64, u64, bool, u64) \{
-    let (base_quantity_filled, quote_quantity_filled, is_success, order_id, _meta_data) = place_limit_order_int(
-        pool,
-        client_order_id,
-        price,
-        quantity,
-        self_matching_prevention,
-        is_bid,
-        expire_timestamp, // Expiration timestamp in ms in absolute value inclusive.
-        restriction,
-        clock,
-        account_cap,
-        false, // don't compute metadata
-        ctx
-    );
-    (base_quantity_filled, quote_quantity_filled, is_success, order_id)
-}
-
- - - -
- - - -## Function `place_limit_order_with_metadata` - -Place a limit order to the order book. -Returns (base quantity filled, quote quantity filled, whether a maker order is being placed, order id of the maker order). -When the limit order is not successfully placed, we return false to indicate that and also returns a meaningless order_id 0. -When the limit order is successfully placed, we return true to indicate that and also the corresponding order_id. -So please check that boolean value first before using the order id. - - -

-public fun place_limit_order_with_metadata<BaseAsset, QuoteAsset>(pool: &mut clob_v2::Pool<BaseAsset, QuoteAsset>, client_order_id: u64, price: u64, quantity: u64, self_matching_prevention: u8, is_bid: bool, expire_timestamp: u64, restriction: u8, clock: &clock::Clock, account_cap: &custodian_v2::AccountCap, ctx: &mut tx_context::TxContext): (u64, u64, bool, u64, vector<clob_v2::MatchedOrderMetadata<BaseAsset, QuoteAsset>>)
-
- - - -
-Implementation - - -

-public fun place_limit_order_with_metadata<BaseAsset, QuoteAsset>(
-    pool: &mut Pool<BaseAsset, QuoteAsset>,
-    client_order_id: u64,
-    price: u64,
-    quantity: u64,
-    self_matching_prevention: u8,
-    is_bid: bool,
-    expire_timestamp: u64, // Expiration timestamp in ms in absolute value inclusive.
-    restriction: u8,
-    clock: &Clock,
-    account_cap: &AccountCap,
-    ctx: &mut TxContext
-): (u64, u64, bool, u64, vector<MatchedOrderMetadata<BaseAsset, QuoteAsset>>) \{
-    let (base_quantity_filled, quote_quantity_filled, is_success, order_id, mut meta_data) = place_limit_order_int(
-        pool,
-        client_order_id,
-        price,
-        quantity,
-        self_matching_prevention,
-        is_bid,
-        expire_timestamp, // Expiration timestamp in ms in absolute value inclusive.
-        restriction,
-        clock,
-        account_cap,
-        true, // return metadata
-        ctx
-    );
-    (base_quantity_filled, quote_quantity_filled, is_success, order_id, option::extract(&mut meta_data))
-}
-
- - - -
- - - -## Function `place_limit_order_int` - - - -

-fun place_limit_order_int<BaseAsset, QuoteAsset>(pool: &mut clob_v2::Pool<BaseAsset, QuoteAsset>, client_order_id: u64, price: u64, quantity: u64, self_matching_prevention: u8, is_bid: bool, expire_timestamp: u64, restriction: u8, clock: &clock::Clock, account_cap: &custodian_v2::AccountCap, compute_metadata: bool, ctx: &mut tx_context::TxContext): (u64, u64, bool, u64, option::Option<vector<clob_v2::MatchedOrderMetadata<BaseAsset, QuoteAsset>>>)
-
- - - -
-Implementation - - -

-fun place_limit_order_int<BaseAsset, QuoteAsset>(
-    pool: &mut Pool<BaseAsset, QuoteAsset>,
-    client_order_id: u64,
-    price: u64,
-    quantity: u64,
-    self_matching_prevention: u8,
-    is_bid: bool,
-    expire_timestamp: u64, // Expiration timestamp in ms in absolute value inclusive.
-    restriction: u8,
-    clock: &Clock,
-    account_cap: &AccountCap,
-    compute_metadata: bool,
-    ctx: &mut TxContext
-): (u64, u64, bool, u64, Option<vector<MatchedOrderMetadata<BaseAsset, QuoteAsset>>>) \{
-    // If limit bid order, check whether the price is lower than the lowest ask order by checking the min_leaf of asks Critbit Tree.
-    // If so, assign the sequence id of the order to be next_bid_order_id and increment next_bid_order_id by 1.
-    // Inject the new order to the bids Critbit Tree according to the price and order id.
-    // Otherwise, find the price level from the asks Critbit Tree that is no greater than the input price.
-    // Match the bid order against the asks Critbit Tree in the same way as a market order but up until the price level found in the previous step.
-    // If the bid order is not completely filled, inject the remaining quantity to the bids Critbit Tree according to the input price and order id.
-    // If limit ask order, vice versa.
-    assert!(self_matching_prevention == CANCEL_OLDEST, EInvalidSelfMatchingPreventionArg);
-    assert!(quantity > 0, EInvalidQuantity);
-    assert!(price > 0, EInvalidPrice);
-    assert!(price % pool.tick_size == 0, EInvalidPrice);
-    assert!(quantity % pool.lot_size == 0, EInvalidQuantity);
-    assert!(expire_timestamp > clock::timestamp_ms(clock), EInvalidExpireTimestamp);
-    let owner = account_owner(account_cap);
-    let original_quantity = quantity;
-    let base_quantity_filled;
-    let quote_quantity_filled;
-    let meta_data = if (is_bid) \{
-        let quote_quantity_original = custodian::account_available_balance<QuoteAsset>(
-            &pool.quote_custodian,
-            owner
-        );
-        let quote_balance = custodian::decrease_user_available_balance<QuoteAsset>(
-            &mut pool.quote_custodian,
-            account_cap,
-            quote_quantity_original,
-        );
-        let (base_balance_filled, quote_balance_left, matched_order_metadata) = match_bid(
-            pool,
-            account_cap,
-            client_order_id,
-            quantity,
-            price,
-            clock::timestamp_ms(clock),
-            quote_balance,
-            compute_metadata
-        );
-        base_quantity_filled = balance::value(&base_balance_filled);
-        quote_quantity_filled = quote_quantity_original - balance::value("e_balance_left);
-
-        custodian::increase_user_available_balance<BaseAsset>(
-            &mut pool.base_custodian,
-            owner,
-            base_balance_filled,
-        );
-        custodian::increase_user_available_balance<QuoteAsset>(
-            &mut pool.quote_custodian,
-            owner,
-            quote_balance_left,
-        );
-
-        matched_order_metadata
-    } else \{
-        let base_balance = custodian::decrease_user_available_balance<BaseAsset>(
-            &mut pool.base_custodian,
-            account_cap,
-            quantity,
-        );
-        let (base_balance_left, quote_balance_filled, matched_order_metadata) = match_ask(
-            pool,
-            account_cap,
-            client_order_id,
-            price,
-            clock::timestamp_ms(clock),
-            base_balance,
-            compute_metadata
-        );
-
-        base_quantity_filled = quantity - balance::value(&base_balance_left);
-        quote_quantity_filled = balance::value("e_balance_filled);
-
-        custodian::increase_user_available_balance<BaseAsset>(
-            &mut pool.base_custodian,
-            owner,
-            base_balance_left,
-        );
-        custodian::increase_user_available_balance<QuoteAsset>(
-            &mut pool.quote_custodian,
-            owner,
-            quote_balance_filled,
-        );
-        matched_order_metadata
-    };
-
-    let order_id;
-    if (restriction == IMMEDIATE_OR_CANCEL) \{
-        return (base_quantity_filled, quote_quantity_filled, false, 0, meta_data)
-    };
-    if (restriction == FILL_OR_KILL) \{
-        assert!(base_quantity_filled == quantity, EOrderCannotBeFullyFilled);
-        return (base_quantity_filled, quote_quantity_filled, false, 0, meta_data)
-    };
-    if (restriction == POST_OR_ABORT) \{
-        assert!(base_quantity_filled == 0, EOrderCannotBeFullyPassive);
-        order_id = inject_limit_order(
-            pool,
-            client_order_id,
-            price,
-            original_quantity,
-            quantity,
-            is_bid,
-            self_matching_prevention,
-            expire_timestamp,
-            account_cap,
-            ctx
-        );
-        return (base_quantity_filled, quote_quantity_filled, true, order_id, meta_data)
-    } else \{
-        assert!(restriction == NO_RESTRICTION, EInvalidRestriction);
-        if (quantity > base_quantity_filled) \{
-            order_id = inject_limit_order(
-                pool,
-                client_order_id,
-                price,
-                original_quantity,
-                quantity - base_quantity_filled,
-                is_bid,
-                self_matching_prevention,
-                expire_timestamp,
-                account_cap,
-                ctx
-            );
-            return (base_quantity_filled, quote_quantity_filled, true, order_id, meta_data)
-        };
-        return (base_quantity_filled, quote_quantity_filled, false, 0, meta_data)
-    }
-}
-
- - - -
- - - -## Function `order_is_bid` - - - -

-fun order_is_bid(order_id: u64): bool
-
- - - -
-Implementation - - -

-fun order_is_bid(order_id: u64): bool \{
-    return order_id < MIN_ASK_ORDER_ID
-}
-
- - - -
- - - -## Function `emit_order_canceled` - - - -

-fun emit_order_canceled<BaseAsset, QuoteAsset>(pool_id: object::ID, order: &clob_v2::Order)
-
- - - -
-Implementation - - -

-fun emit_order_canceled<BaseAsset, QuoteAsset>(
-    pool_id: ID,
-    order: &Order
-) \{
-    event::emit(OrderCanceled<BaseAsset, QuoteAsset> \{
-        pool_id,
-        client_order_id: order.client_order_id,
-        order_id: order.order_id,
-        is_bid: order.is_bid,
-        owner: order.owner,
-        original_quantity: order.original_quantity,
-        base_asset_quantity_canceled: order.quantity,
-        price: order.price
-    })
-}
-
- - - -
- - - -## Function `emit_order_filled` - - - -

-fun emit_order_filled<BaseAsset, QuoteAsset>(pool_id: object::ID, taker_client_id: u64, taker_address: address, order: &clob_v2::Order, base_asset_quantity_filled: u64, taker_commission: u64, maker_rebates: u64)
-
- - - -
-Implementation - - -

-fun emit_order_filled<BaseAsset, QuoteAsset>(
-    pool_id: ID,
-    taker_client_id: u64,
-    taker_address: address,
-    order: &Order,
-    base_asset_quantity_filled: u64,
-    taker_commission: u64,
-    maker_rebates: u64
-) \{
-    event::emit(OrderFilled<BaseAsset, QuoteAsset> \{
-        pool_id,
-        order_id: order.order_id,
-        taker_client_order_id: taker_client_id,
-        taker_address,
-        maker_client_order_id: order.client_order_id,
-        is_bid: order.is_bid,
-        maker_address: order.owner,
-        original_quantity: order.original_quantity,
-        base_asset_quantity_filled,
-        // order.quantity = base_asset_quantity_filled + base_asset_quantity_remaining
-        // This guarantees that the subtraction will not underflow
-        base_asset_quantity_remaining: order.quantity - base_asset_quantity_filled,
-        price: order.price,
-        taker_commission,
-        maker_rebates
-    })
-}
-
- - - -
- - - -## Function `cancel_order` - -Cancel and opening order. -Abort if order_id is invalid or if the order is not submitted by the transaction sender. - - -

-public fun cancel_order<BaseAsset, QuoteAsset>(pool: &mut clob_v2::Pool<BaseAsset, QuoteAsset>, order_id: u64, account_cap: &custodian_v2::AccountCap)
-
- - - -
-Implementation - - -

-public fun cancel_order<BaseAsset, QuoteAsset>(
-    pool: &mut Pool<BaseAsset, QuoteAsset>,
-    order_id: u64,
-    account_cap: &AccountCap
-) \{
-    // First check the highest bit of the order id to see whether it's bid or ask.
-    // Then retrieve the price using the order id.
-    // Using the price to retrieve the corresponding PriceLevel from the bids / asks Critbit Tree.
-    // Retrieve and remove the order from open orders of the PriceLevel.
-    let owner = account_owner(account_cap);
-    assert!(contains(&pool.usr_open_orders, owner), EInvalidUser);
-    let usr_open_orders = borrow_mut(&mut pool.usr_open_orders, owner);
-    assert!(linked_table::contains(usr_open_orders, order_id), EInvalidOrderId);
-    let tick_price = *linked_table::borrow(usr_open_orders, order_id);
-    let is_bid = order_is_bid(order_id);
-    let (tick_exists, tick_index) = find_leaf(
-        if (is_bid) \{ &pool.bids } else \{ &pool.asks },
-        tick_price);
-    assert!(tick_exists, EInvalidOrderId);
-    let order = remove_order(
-        if (is_bid) \{ &mut pool.bids } else \{ &mut pool.asks },
-        usr_open_orders,
-        tick_index,
-        order_id,
-        owner
-    );
-    if (is_bid) \{
-        let (_, balance_locked) = clob_math::unsafe_mul_round(order.quantity, order.price);
-        custodian::unlock_balance(&mut pool.quote_custodian, owner, balance_locked);
-    } else \{
-        custodian::unlock_balance(&mut pool.base_custodian, owner, order.quantity);
-    };
-    emit_order_canceled<BaseAsset, QuoteAsset>(*object::uid_as_inner(&pool.id), &order);
-}
-
- - - -
- - - -## Function `remove_order` - - - -

-fun remove_order(open_orders: &mut critbit::CritbitTree<clob_v2::TickLevel>, usr_open_orders: &mut linked_table::LinkedTable<u64, u64>, tick_index: u64, order_id: u64, owner: address): clob_v2::Order
-
- - - -
-Implementation - - -

-fun remove_order(
-    open_orders: &mut CritbitTree<TickLevel>,
-    usr_open_orders: &mut LinkedTable<u64, u64>,
-    tick_index: u64,
-    order_id: u64,
-    owner: address,
-): Order \{
-    linked_table::remove(usr_open_orders, order_id);
-    let tick_level = borrow_leaf_by_index(open_orders, tick_index);
-    assert!(linked_table::contains(&tick_level.open_orders, order_id), EInvalidOrderId);
-    let mut_tick_level = borrow_mut_leaf_by_index(open_orders, tick_index);
-    let order = linked_table::remove(&mut mut_tick_level.open_orders, order_id);
-    assert!(order.owner == owner, EUnauthorizedCancel);
-    if (linked_table::is_empty(&mut_tick_level.open_orders)) \{
-        destroy_empty_level(remove_leaf_by_index(open_orders, tick_index));
-    };
-    order
-}
-
- - - -
- - - -## Function `cancel_all_orders` - - - -

-public fun cancel_all_orders<BaseAsset, QuoteAsset>(pool: &mut clob_v2::Pool<BaseAsset, QuoteAsset>, account_cap: &custodian_v2::AccountCap)
-
- - - -
-Implementation - - -

-public fun cancel_all_orders<BaseAsset, QuoteAsset>(
-    pool: &mut Pool<BaseAsset, QuoteAsset>,
-    account_cap: &AccountCap
-) \{
-    let pool_id = *object::uid_as_inner(&pool.id);
-    let owner = account_owner(account_cap);
-    assert!(contains(&pool.usr_open_orders, owner), EInvalidUser);
-    let usr_open_order_ids = table::borrow_mut(&mut pool.usr_open_orders, owner);
-    let mut canceled_order_events = vector[];
-    while (!linked_table::is_empty(usr_open_order_ids)) \{
-        let order_id = *option::borrow(linked_table::back(usr_open_order_ids));
-        let order_price = *linked_table::borrow(usr_open_order_ids, order_id);
-        let is_bid = order_is_bid(order_id);
-        let open_orders =
-            if (is_bid) \{ &mut pool.bids }
-            else \{ &mut pool.asks };
-        let (_, tick_index) = critbit::find_leaf(open_orders, order_price);
-        let order = remove_order(
-            open_orders,
-            usr_open_order_ids,
-            tick_index,
-            order_id,
-            owner
-        );
-        if (is_bid) \{
-            let (_, balance_locked) = clob_math::unsafe_mul_round(order.quantity, order.price);
-            custodian::unlock_balance(&mut pool.quote_custodian, owner, balance_locked);
-        } else \{
-            custodian::unlock_balance(&mut pool.base_custodian, owner, order.quantity);
-        };
-        let canceled_order_event = AllOrdersCanceledComponent<BaseAsset, QuoteAsset> \{
-            client_order_id: order.client_order_id,
-            order_id: order.order_id,
-            is_bid: order.is_bid,
-            owner: order.owner,
-            original_quantity: order.original_quantity,
-            base_asset_quantity_canceled: order.quantity,
-            price: order.price
-        };
-
-        vector::push_back(&mut canceled_order_events, canceled_order_event);
-    };
-
-    if (!vector::is_empty(&canceled_order_events)) \{
-        event::emit(AllOrdersCanceled<BaseAsset, QuoteAsset> \{
-            pool_id,
-            orders_canceled: canceled_order_events,
-        });
-    };
-}
-
- - - -
- - - -## Function `batch_cancel_order` - -Batch cancel limit orders to save gas cost. -Abort if any of the order_ids are not submitted by the sender. -Skip any order_id that is invalid. -Note that this function can reduce gas cost even further if caller has multiple orders at the same price level, -and if orders with the same price are grouped together in the vector. -For example, if we have the following order_id to price mapping, \{0: 100., 1: 200., 2: 100., 3: 200.}. -Grouping order_ids like [0, 2, 1, 3] would make it the most gas efficient. - - -

-public fun batch_cancel_order<BaseAsset, QuoteAsset>(pool: &mut clob_v2::Pool<BaseAsset, QuoteAsset>, order_ids: vector<u64>, account_cap: &custodian_v2::AccountCap)
-
- - - -
-Implementation - - -

-public fun batch_cancel_order<BaseAsset, QuoteAsset>(
-    pool: &mut Pool<BaseAsset, QuoteAsset>,
-    order_ids: vector<u64>,
-    account_cap: &AccountCap
-) \{
-    let pool_id = *object::uid_as_inner(&pool.id);
-    // First group the order ids according to price level,
-    // so that we don't have to retrieve the PriceLevel multiple times if there are orders at the same price level.
-    // Iterate over each price level, retrieve the corresponding PriceLevel.
-    // Iterate over the order ids that need to be canceled at that price level,
-    // retrieve and remove the order from open orders of the PriceLevel.
-    let owner = account_owner(account_cap);
-    assert!(contains(&pool.usr_open_orders, owner), 0);
-    let mut tick_index: u64 = 0;
-    let mut tick_price: u64 = 0;
-    let n_order = vector::length(&order_ids);
-    let mut i_order = 0;
-    let usr_open_orders = borrow_mut(&mut pool.usr_open_orders, owner);
-    let mut canceled_order_events = vector[];
-
-    while (i_order < n_order) \{
-        let order_id = *vector::borrow(&order_ids, i_order);
-        assert!(linked_table::contains(usr_open_orders, order_id), EInvalidOrderId);
-        let new_tick_price = *linked_table::borrow(usr_open_orders, order_id);
-        let is_bid = order_is_bid(order_id);
-        if (new_tick_price != tick_price) \{
-            tick_price = new_tick_price;
-            let (tick_exists, new_tick_index) = find_leaf(
-                if (is_bid) \{ &pool.bids } else \{ &pool.asks },
-                tick_price
-            );
-            assert!(tick_exists, EInvalidTickPrice);
-            tick_index = new_tick_index;
-        };
-        let order = remove_order(
-            if (is_bid) \{ &mut pool.bids } else \{ &mut pool.asks },
-            usr_open_orders,
-            tick_index,
-            order_id,
-            owner
-        );
-        if (is_bid) \{
-            let (_is_round_down, balance_locked) = clob_math::unsafe_mul_round(order.quantity, order.price);
-            custodian::unlock_balance(&mut pool.quote_custodian, owner, balance_locked);
-        } else \{
-            custodian::unlock_balance(&mut pool.base_custodian, owner, order.quantity);
-        };
-        let canceled_order_event = AllOrdersCanceledComponent<BaseAsset, QuoteAsset> \{
-            client_order_id: order.client_order_id,
-            order_id: order.order_id,
-            is_bid: order.is_bid,
-            owner: order.owner,
-            original_quantity: order.original_quantity,
-            base_asset_quantity_canceled: order.quantity,
-            price: order.price
-        };
-        vector::push_back(&mut canceled_order_events, canceled_order_event);
-
-        i_order = i_order + 1;
-    };
-
-    if (!vector::is_empty(&canceled_order_events)) \{
-        event::emit(AllOrdersCanceled<BaseAsset, QuoteAsset> \{
-            pool_id,
-            orders_canceled: canceled_order_events,
-        });
-    };
-}
-
- - - -
- - - -## Function `clean_up_expired_orders` - -Clean up expired orders -Note that this function can reduce gas cost if orders -with the same price are grouped together in the vector because we would not need the computation to find the tick_index. -For example, if we have the following order_id to price mapping, \{0: 100., 1: 200., 2: 100., 3: 200.}. -Grouping order_ids like [0, 2, 1, 3] would make it the most gas efficient. -Order owners should be the owner addresses from the account capacities which placed the orders, -and they should correspond to the order IDs one by one. - - -

-public fun clean_up_expired_orders<BaseAsset, QuoteAsset>(pool: &mut clob_v2::Pool<BaseAsset, QuoteAsset>, clock: &clock::Clock, order_ids: vector<u64>, order_owners: vector<address>)
-
- - - -
-Implementation - - -

-public fun clean_up_expired_orders<BaseAsset, QuoteAsset>(
-    pool: &mut Pool<BaseAsset, QuoteAsset>,
-    clock: &Clock,
-    order_ids: vector<u64>,
-    order_owners: vector<address>
-) \{
-    let pool_id = *object::uid_as_inner(&pool.id);
-    let now = clock::timestamp_ms(clock);
-    let n_order = vector::length(&order_ids);
-    assert!(n_order == vector::length(&order_owners), ENotEqual);
-    let mut i_order = 0;
-    let mut tick_index: u64 = 0;
-    let mut tick_price: u64 = 0;
-    let mut canceled_order_events = vector[];
-    while (i_order < n_order) \{
-        let order_id = *vector::borrow(&order_ids, i_order);
-        let owner = *vector::borrow(&order_owners, i_order);
-        if (!table::contains(&pool.usr_open_orders, owner)) \{ continue };
-        let usr_open_orders = borrow_mut(&mut pool.usr_open_orders, owner);
-        if (!linked_table::contains(usr_open_orders, order_id)) \{ continue };
-        let new_tick_price = *linked_table::borrow(usr_open_orders, order_id);
-        let is_bid = order_is_bid(order_id);
-        let open_orders = if (is_bid) \{ &mut pool.bids } else \{ &mut pool.asks };
-        if (new_tick_price != tick_price) \{
-            tick_price = new_tick_price;
-            let (tick_exists, new_tick_index) = find_leaf(
-                open_orders,
-                tick_price
-            );
-            assert!(tick_exists, EInvalidTickPrice);
-            tick_index = new_tick_index;
-        };
-        let order = remove_order(open_orders, usr_open_orders, tick_index, order_id, owner);
-        assert!(order.expire_timestamp < now, EInvalidExpireTimestamp);
-        if (is_bid) \{
-            let (_is_round_down, balance_locked) = clob_math::unsafe_mul_round(order.quantity, order.price);
-            custodian::unlock_balance(&mut pool.quote_custodian, owner, balance_locked);
-        } else \{
-            custodian::unlock_balance(&mut pool.base_custodian, owner, order.quantity);
-        };
-        let canceled_order_event = AllOrdersCanceledComponent<BaseAsset, QuoteAsset> \{
-            client_order_id: order.client_order_id,
-            order_id: order.order_id,
-            is_bid: order.is_bid,
-            owner: order.owner,
-            original_quantity: order.original_quantity,
-            base_asset_quantity_canceled: order.quantity,
-            price: order.price
-        };
-        vector::push_back(&mut canceled_order_events, canceled_order_event);
-
-        i_order = i_order + 1;
-    };
-
-    if (!vector::is_empty(&canceled_order_events)) \{
-        event::emit(AllOrdersCanceled<BaseAsset, QuoteAsset> \{
-            pool_id,
-            orders_canceled: canceled_order_events,
-        });
-    };
-}
-
- - - -
- - - -## Function `list_open_orders` - - - -

-public fun list_open_orders<BaseAsset, QuoteAsset>(pool: &clob_v2::Pool<BaseAsset, QuoteAsset>, account_cap: &custodian_v2::AccountCap): vector<clob_v2::Order>
-
- - - -
-Implementation - - -

-public fun list_open_orders<BaseAsset, QuoteAsset>(
-    pool: &Pool<BaseAsset, QuoteAsset>,
-    account_cap: &AccountCap
-): vector<Order> \{
-    let owner = account_owner(account_cap);
-    let mut open_orders = vector::empty<Order>();
-    if (!usr_open_orders_exist(pool, owner)) \{
-        return open_orders
-    };
-    let usr_open_order_ids = table::borrow(&pool.usr_open_orders, owner);
-    let mut order_id = linked_table::front(usr_open_order_ids);
-    while (!option::is_none(order_id)) \{
-        let order_price = *linked_table::borrow(usr_open_order_ids, *option::borrow(order_id));
-        let tick_level =
-            if (order_is_bid(*option::borrow(order_id))) borrow_leaf_by_key(&pool.bids, order_price)
-            else borrow_leaf_by_key(&pool.asks, order_price);
-        let order = linked_table::borrow(&tick_level.open_orders, *option::borrow(order_id));
-        vector::push_back(&mut open_orders, Order \{
-            order_id: order.order_id,
-            client_order_id: order.client_order_id,
-            price: order.price,
-            original_quantity: order.original_quantity,
-            quantity: order.quantity,
-            is_bid: order.is_bid,
-            owner: order.owner,
-            expire_timestamp: order.expire_timestamp,
-            self_matching_prevention: order.self_matching_prevention
-        });
-        order_id = linked_table::next(usr_open_order_ids, *option::borrow(order_id));
-    };
-    open_orders
-}
-
- - - -
- - - -## Function `account_balance` - -query user balance inside custodian - - -

-public fun account_balance<BaseAsset, QuoteAsset>(pool: &clob_v2::Pool<BaseAsset, QuoteAsset>, account_cap: &custodian_v2::AccountCap): (u64, u64, u64, u64)
-
- - - -
-Implementation - - -

-public fun account_balance<BaseAsset, QuoteAsset>(
-    pool: &Pool<BaseAsset, QuoteAsset>,
-    account_cap: &AccountCap
-): (u64, u64, u64, u64) \{
-    let owner = account_owner(account_cap);
-    let (base_avail, base_locked) = custodian::account_balance(&pool.base_custodian, owner);
-    let (quote_avail, quote_locked) = custodian::account_balance(&pool.quote_custodian, owner);
-    (base_avail, base_locked, quote_avail, quote_locked)
-}
-
- - - -
- - - -## Function `get_market_price` - -Query the market price of order book -returns (best_bid_price, best_ask_price) if there exists -bid/ask order in the order book, otherwise returns None - - -

-public fun get_market_price<BaseAsset, QuoteAsset>(pool: &clob_v2::Pool<BaseAsset, QuoteAsset>): (option::Option<u64>, option::Option<u64>)
-
- - - -
-Implementation - - -

-public fun get_market_price<BaseAsset, QuoteAsset>(
-    pool: &Pool<BaseAsset, QuoteAsset>
-): (Option<u64>, Option<u64>)\{
-    let bid_price = if (!critbit::is_empty(&pool.bids)) \{
-        let (result, _) = critbit::max_leaf(&pool.bids);
-        option::some<u64>(result)
-    } else \{
-        option::none<u64>()
-    };
-    let ask_price = if (!critbit::is_empty(&pool.asks)) \{
-        let (result, _) = critbit::min_leaf(&pool.asks);
-        option::some<u64>(result)
-    } else \{
-        option::none<u64>()
-    };
-    return (bid_price, ask_price)
-}
-
- - - -
- - - -## Function `get_level2_book_status_bid_side` - -Enter a price range and return the level2 order depth of all valid prices within this price range in bid side -returns two vectors of u64 -The previous is a list of all valid prices -The latter is the corresponding depth list - - -

-public fun get_level2_book_status_bid_side<BaseAsset, QuoteAsset>(pool: &clob_v2::Pool<BaseAsset, QuoteAsset>, price_low: u64, price_high: u64, clock: &clock::Clock): (vector<u64>, vector<u64>)
-
- - - -
-Implementation - - -

-public fun get_level2_book_status_bid_side<BaseAsset, QuoteAsset>(
-    pool: &Pool<BaseAsset, QuoteAsset>,
-    mut price_low: u64,
-    mut price_high: u64,
-    clock: &Clock
-): (vector<u64>, vector<u64>) \{
-    let mut price_vec = vector::empty<u64>();
-    let mut depth_vec = vector::empty<u64>();
-    if (critbit::is_empty(&pool.bids)) \{ return (price_vec, depth_vec) };
-    let (price_low_, _) = critbit::min_leaf(&pool.bids);
-    let (price_high_, _) = critbit::max_leaf(&pool.bids);
-
-    // If price_low is greater than the highest element in the tree, we return empty
-    if (price_low > price_high_) \{
-        return (price_vec, depth_vec)
-    };
-
-    if (price_low < price_low_) price_low = price_low_;
-    if (price_high > price_high_) price_high = price_high_;
-    let closest_low = critbit::find_closest_key(&pool.bids, price_low);
-    let closest_high = critbit::find_closest_key(&pool.bids, price_high);
-    if (price_low <= closest_low)\{
-        price_low = closest_low;
-    } else \{
-        (price_low, _) = critbit::next_leaf(&pool.bids, closest_low);
-    };
-    if (price_high >= closest_high)\{
-        price_high = closest_high;
-    } else \{
-        (price_high, _) = critbit::previous_leaf(&pool.bids, closest_high);
-    };
-
-    while (price_low <= price_high) \{
-        let depth = get_level2_book_status(
-            &pool.bids,
-            price_low,
-            clock::timestamp_ms(clock)
-        );
-        if (depth != 0) \{
-            vector::push_back(&mut price_vec, price_low);
-            vector::push_back(&mut depth_vec, depth);
-        };
-        let (next_price, _) = critbit::next_leaf(&pool.bids, price_low);
-        if (next_price == 0) \{ break }
-        else \{ price_low = next_price };
-    };
-    (price_vec, depth_vec)
-}
-
- - - -
- - - -## Function `get_level2_book_status_ask_side` - -Enter a price range and return the level2 order depth of all valid prices within this price range in ask side -returns two vectors of u64 -The previous is a list of all valid prices -The latter is the corresponding depth list - - -

-public fun get_level2_book_status_ask_side<BaseAsset, QuoteAsset>(pool: &clob_v2::Pool<BaseAsset, QuoteAsset>, price_low: u64, price_high: u64, clock: &clock::Clock): (vector<u64>, vector<u64>)
-
- - - -
-Implementation - - -

-public fun get_level2_book_status_ask_side<BaseAsset, QuoteAsset>(
-    pool: &Pool<BaseAsset, QuoteAsset>,
-    mut price_low: u64,
-    mut price_high: u64,
-    clock: &Clock
-): (vector<u64>, vector<u64>) \{
-    let mut price_vec = vector::empty<u64>();
-    let mut depth_vec = vector::empty<u64>();
-    if (critbit::is_empty(&pool.asks)) \{ return (price_vec, depth_vec) };
-    let (price_low_, _) = critbit::min_leaf(&pool.asks);
-    let (price_high_, _) = critbit::max_leaf(&pool.asks);
-
-    // Price_high is less than the lowest leaf in the tree then we return an empty array
-    if (price_high < price_low_) \{
-        return (price_vec, depth_vec)
-    };
-
-    if (price_low < price_low_) price_low = price_low_;
-    if (price_high > price_high_) price_high = price_high_;
-    let closest_low = critbit::find_closest_key(&pool.asks, price_low);
-    let closest_high = critbit::find_closest_key(&pool.asks, price_high);
-    if (price_low <= closest_low)\{
-        price_low = closest_low;
-    } else \{
-        (price_low, _) = critbit::next_leaf(&pool.bids, closest_low);
-    };
-    if (price_high >= closest_high)\{
-        price_high = closest_high;
-    } else \{
-        (price_high, _) = critbit::previous_leaf(&pool.bids, closest_high);
-    };
-
-    while (price_low <= price_high) \{
-        let depth = get_level2_book_status(
-            &pool.asks,
-            price_low,
-            clock::timestamp_ms(clock)
-        );
-        if (depth != 0) \{
-            vector::push_back(&mut price_vec, price_low);
-            vector::push_back(&mut depth_vec, depth);
-        };
-        let (next_price, _) = critbit::next_leaf(&pool.asks, price_low);
-        if (next_price == 0) \{ break }
-        else \{ price_low = next_price };
-    };
-    (price_vec, depth_vec)
-}
-
- - - -
- - - -## Function `get_level2_book_status` - -internal func to retrieve single depth of a tick price - - -

-fun get_level2_book_status(open_orders: &critbit::CritbitTree<clob_v2::TickLevel>, price: u64, time_stamp: u64): u64
-
- - - -
-Implementation - - -

-fun get_level2_book_status(
-    open_orders: &CritbitTree<TickLevel>,
-    price: u64,
-    time_stamp: u64
-): u64 \{
-    let tick_level = critbit::borrow_leaf_by_key(open_orders, price);
-    let tick_open_orders = &tick_level.open_orders;
-    let mut depth = 0;
-    let mut order_id = linked_table::front(tick_open_orders);
-    let mut order: &Order;
-    while (!option::is_none(order_id)) \{
-        order = linked_table::borrow(tick_open_orders, *option::borrow(order_id));
-        if (order.expire_timestamp > time_stamp) depth = depth + order.quantity;
-        order_id = linked_table::next(tick_open_orders, *option::borrow(order_id));
-    };
-    depth
-}
-
- - - -
- - - -## Function `get_order_status` - - - -

-public fun get_order_status<BaseAsset, QuoteAsset>(pool: &clob_v2::Pool<BaseAsset, QuoteAsset>, order_id: u64, account_cap: &custodian_v2::AccountCap): &clob_v2::Order
-
- - - -
-Implementation - - -

-public fun get_order_status<BaseAsset, QuoteAsset>(
-    pool: &Pool<BaseAsset, QuoteAsset>,
-    order_id: u64,
-    account_cap: &AccountCap
-): &Order \{
-    let owner = account_owner(account_cap);
-    assert!(table::contains(&pool.usr_open_orders, owner), EInvalidUser);
-    let usr_open_order_ids = table::borrow(&pool.usr_open_orders, owner);
-    assert!(linked_table::contains(usr_open_order_ids, order_id), EInvalidOrderId);
-    let order_price = *linked_table::borrow(usr_open_order_ids, order_id);
-    let open_orders =
-        if (order_id < MIN_ASK_ORDER_ID) \{ &pool.bids }
-        else \{ &pool.asks };
-    let tick_level = critbit::borrow_leaf_by_key(open_orders, order_price);
-    let tick_open_orders = &tick_level.open_orders;
-    let order = linked_table::borrow(tick_open_orders, order_id);
-    order
-}
-
- - - -
- - - -## Function `matched_order_metadata` - - - -

-fun matched_order_metadata<BaseAsset, QuoteAsset>(pool_id: object::ID, taker_address: address, order: &clob_v2::Order, base_asset_quantity_filled: u64, taker_commission: u64, maker_rebates: u64): clob_v2::MatchedOrderMetadata<BaseAsset, QuoteAsset>
-
- - - -
-Implementation - - -

-fun matched_order_metadata<BaseAsset, QuoteAsset>(
-    pool_id: ID,
-    taker_address: address,
-    order: &Order,
-    base_asset_quantity_filled: u64,
-    taker_commission: u64,
-    maker_rebates: u64
-): MatchedOrderMetadata<BaseAsset, QuoteAsset>\{
-    MatchedOrderMetadata<BaseAsset, QuoteAsset> \{
-        pool_id,
-        order_id: order.order_id,
-        is_bid: order.is_bid,
-        taker_address,
-        maker_address: order.owner,
-        base_asset_quantity_filled,
-        price: order.price,
-        taker_commission,
-        maker_rebates
-    }
-}
-
- - - -
- - - -## Function `matched_order_metadata_info` - - - -

-public fun matched_order_metadata_info<BaseAsset, QuoteAsset>(matched_order_metadata: &clob_v2::MatchedOrderMetadata<BaseAsset, QuoteAsset>): (object::ID, u64, bool, address, address, u64, u64, u64, u64)
-
- - - -
-Implementation - - -

-public fun matched_order_metadata_info<BaseAsset, QuoteAsset>(
-    matched_order_metadata: &MatchedOrderMetadata<BaseAsset, QuoteAsset>
-) : ( ID, u64, bool, address, address, u64, u64, u64, u64) \{
-    (
-        matched_order_metadata.pool_id,
-        matched_order_metadata.order_id,
-        matched_order_metadata.is_bid,
-        matched_order_metadata.taker_address,
-        matched_order_metadata.maker_address,
-        matched_order_metadata.base_asset_quantity_filled,
-        matched_order_metadata.price,
-        matched_order_metadata.taker_commission,
-        matched_order_metadata.maker_rebates
-    )
-}
-
- - - -
- - - -## Function `asks` - - - -

-public fun asks<BaseAsset, QuoteAsset>(pool: &clob_v2::Pool<BaseAsset, QuoteAsset>): &critbit::CritbitTree<clob_v2::TickLevel>
-
- - - -
-Implementation - - -

-public fun asks<BaseAsset, QuoteAsset>(pool: &Pool<BaseAsset, QuoteAsset>): &CritbitTree<TickLevel> \{
-    &pool.asks
-}
-
- - - -
- - - -## Function `bids` - - - -

-public fun bids<BaseAsset, QuoteAsset>(pool: &clob_v2::Pool<BaseAsset, QuoteAsset>): &critbit::CritbitTree<clob_v2::TickLevel>
-
- - - -
-Implementation - - -

-public fun bids<BaseAsset, QuoteAsset>(pool: &Pool<BaseAsset, QuoteAsset>): &CritbitTree<TickLevel> \{
-    &pool.bids
-}
-
- - - -
- - - -## Function `tick_size` - - - -

-public fun tick_size<BaseAsset, QuoteAsset>(pool: &clob_v2::Pool<BaseAsset, QuoteAsset>): u64
-
- - - -
-Implementation - - -

-public fun tick_size<BaseAsset, QuoteAsset>(pool: &Pool<BaseAsset, QuoteAsset>): u64 \{
-    pool.tick_size
-}
-
- - - -
- - - -## Function `maker_rebate_rate` - - - -

-public fun maker_rebate_rate<BaseAsset, QuoteAsset>(pool: &clob_v2::Pool<BaseAsset, QuoteAsset>): u64
-
- - - -
-Implementation - - -

-public fun maker_rebate_rate<BaseAsset, QuoteAsset>(pool: &Pool<BaseAsset, QuoteAsset>): u64 \{
-    pool.maker_rebate_rate
-}
-
- - - -
- - - -## Function `taker_fee_rate` - - - -

-public fun taker_fee_rate<BaseAsset, QuoteAsset>(pool: &clob_v2::Pool<BaseAsset, QuoteAsset>): u64
-
- - - -
-Implementation - - -

-public fun taker_fee_rate<BaseAsset, QuoteAsset>(pool: &Pool<BaseAsset, QuoteAsset>): u64 \{
-    pool.taker_fee_rate
-}
-
- - - -
- - - -## Function `pool_size` - - - -

-public fun pool_size<BaseAsset, QuoteAsset>(pool: &clob_v2::Pool<BaseAsset, QuoteAsset>): u64
-
- - - -
-Implementation - - -

-public fun pool_size<BaseAsset, QuoteAsset>(pool: &Pool<BaseAsset, QuoteAsset>): u64 \{
-    critbit::size(&pool.asks) + critbit::size(&pool.bids)
-}
-
- - - -
- - - -## Function `open_orders` - - - -

-public fun open_orders(tick_level: &clob_v2::TickLevel): &linked_table::LinkedTable<u64, clob_v2::Order>
-
- - - -
-Implementation - - -

-public fun open_orders(tick_level: &TickLevel): &LinkedTable<u64, Order> \{
-    &tick_level.open_orders
-}
-
- - - -
- - - -## Function `order_id` - - - -

-public fun order_id(order: &clob_v2::Order): u64
-
- - - -
-Implementation - - -

-public fun order_id(order: &Order): u64 \{
-    order.order_id
-}
-
- - - -
- - - -## Function `tick_level` - - - -

-public fun tick_level(order: &clob_v2::Order): u64
-
- - - -
-Implementation - - -

-public fun tick_level(order: &Order): u64 \{
-    order.price
-}
-
- - - -
- - - -## Function `original_quantity` - - - -

-public fun original_quantity(order: &clob_v2::Order): u64
-
- - - -
-Implementation - - -

-public fun original_quantity(order: &Order): u64 \{
-    order.original_quantity
-}
-
- - - -
- - - -## Function `quantity` - - - -

-public fun quantity(order: &clob_v2::Order): u64
-
- - - -
-Implementation - - -

-public fun quantity(order: &Order): u64 \{
-    order.quantity
-}
-
- - - -
- - - -## Function `is_bid` - - - -

-public fun is_bid(order: &clob_v2::Order): bool
-
- - - -
-Implementation - - -

-public fun is_bid(order: &Order): bool \{
-    order.is_bid
-}
-
- - - -
- - - -## Function `owner` - - - -

-public fun owner(order: &clob_v2::Order): address
-
- - - -
-Implementation - - -

-public fun owner(order: &Order): address \{
-    order.owner
-}
-
- - - -
- - - -## Function `expire_timestamp` - - - -

-public fun expire_timestamp(order: &clob_v2::Order): u64
-
- - - -
-Implementation - - -

-public fun expire_timestamp(order: &Order): u64 \{
-    order.expire_timestamp
-}
-
- - - -
- - - -## Function `quote_asset_trading_fees_value` - - - -

-public fun quote_asset_trading_fees_value<BaseAsset, QuoteAsset>(pool: &clob_v2::Pool<BaseAsset, QuoteAsset>): u64
-
- - - -
-Implementation - - -

-public fun quote_asset_trading_fees_value<BaseAsset, QuoteAsset>(pool: &Pool<BaseAsset, QuoteAsset>): u64 \{
-    balance::value(&pool.quote_asset_trading_fees)
-}
-
- - - -
- - - -## Function `clone_order` - - - -

-public(friend) fun clone_order(order: &clob_v2::Order): clob_v2::Order
-
- - - -
-Implementation - - -

-public(package) fun clone_order(order: &Order): Order \{
-    Order \{
-        order_id: order.order_id,
-        client_order_id: order.client_order_id,
-        price: order.price,
-        original_quantity: order.original_quantity,
-        quantity: order.quantity,
-        is_bid: order.is_bid,
-        owner: order.owner,
-        expire_timestamp: order.expire_timestamp,
-        self_matching_prevention: order.self_matching_prevention
-    }
-}
-
- - - -
diff --git a/crates/iota-framework/docs/deepbook/critbit.mdx b/crates/iota-framework/docs/deepbook/critbit.mdx deleted file mode 100644 index 268e8d64740..00000000000 --- a/crates/iota-framework/docs/deepbook/critbit.mdx +++ /dev/null @@ -1,1080 +0,0 @@ ---- -title: Module `0xdee9::critbit` ---- -import Link from '@docusaurus/Link'; - - - - -- [Struct `Leaf`](#0xdee9_critbit_Leaf) -- [Struct `InternalNode`](#0xdee9_critbit_InternalNode) -- [Struct `CritbitTree`](#0xdee9_critbit_CritbitTree) -- [Constants](#@Constants_0) -- [Function `new`](#0xdee9_critbit_new) -- [Function `size`](#0xdee9_critbit_size) -- [Function `is_empty`](#0xdee9_critbit_is_empty) -- [Function `min_leaf`](#0xdee9_critbit_min_leaf) -- [Function `max_leaf`](#0xdee9_critbit_max_leaf) -- [Function `previous_leaf`](#0xdee9_critbit_previous_leaf) -- [Function `next_leaf`](#0xdee9_critbit_next_leaf) -- [Function `left_most_leaf`](#0xdee9_critbit_left_most_leaf) -- [Function `right_most_leaf`](#0xdee9_critbit_right_most_leaf) -- [Function `insert_leaf`](#0xdee9_critbit_insert_leaf) -- [Function `find_leaf`](#0xdee9_critbit_find_leaf) -- [Function `find_closest_key`](#0xdee9_critbit_find_closest_key) -- [Function `remove_leaf_by_index`](#0xdee9_critbit_remove_leaf_by_index) -- [Function `borrow_mut_leaf_by_index`](#0xdee9_critbit_borrow_mut_leaf_by_index) -- [Function `borrow_leaf_by_index`](#0xdee9_critbit_borrow_leaf_by_index) -- [Function `borrow_leaf_by_key`](#0xdee9_critbit_borrow_leaf_by_key) -- [Function `drop`](#0xdee9_critbit_drop) -- [Function `destroy_empty`](#0xdee9_critbit_destroy_empty) -- [Function `get_closest_leaf_index_by_key`](#0xdee9_critbit_get_closest_leaf_index_by_key) -- [Function `update_child`](#0xdee9_critbit_update_child) -- [Function `is_left_child`](#0xdee9_critbit_is_left_child) - - -

-use 0x2::table;
-use 0x2::tx_context;
-use 0xdee9::math;
-
- - - - - -## Struct `Leaf` - - - -

-struct Leaf<V> has drop, store
-
- - - -
-Fields - - -
-
- -key: u64 -
-
- -
-
- -value: V -
-
- -
-
- -parent: u64 -
-
- -
-
- - -
- - - -## Struct `InternalNode` - - - -

-struct InternalNode has drop, store
-
- - - -
-Fields - - -
-
- -mask: u64 -
-
- -
-
- -left_child: u64 -
-
- -
-
- -right_child: u64 -
-
- -
-
- -parent: u64 -
-
- -
-
- - -
- - - -## Struct `CritbitTree` - - - -

-struct CritbitTree<V: store> has store
-
- - - -
-Fields - - -
-
- -root: u64 -
-
- -
-
- -internal_nodes: table::Table<u64, critbit::InternalNode> -
-
- -
-
- -leaves: table::Table<u64, critbit::Leaf<V>> -
-
- -
-
- -min_leaf: u64 -
-
- -
-
- -max_leaf: u64 -
-
- -
-
- -next_internal_node_index: u64 -
-
- -
-
- -next_leaf_index: u64 -
-
- -
-
- - -
- - - -## Constants - - - - - - -

-const EExceedCapacity: u64 = 2;
-
- - - - - - - -

-const EIndexOutOfRange: u64 = 7;
-
- - - - - - - -

-const EKeyAlreadyExist: u64 = 4;
-
- - - - - - - -

-const ELeafNotExist: u64 = 5;
-
- - - - - - - -

-const ENullParent: u64 = 8;
-
- - - - - - - -

-const ETreeNotEmpty: u64 = 3;
-
- - - - - - - -

-const MAX_CAPACITY: u64 = 9223372036854775807;
-
- - - - - - - -

-const MAX_U64: u64 = 18446744073709551615;
-
- - - - - - - -

-const PARTITION_INDEX: u64 = 9223372036854775808;
-
- - - - - -## Function `new` - - - -

-public(friend) fun new<V: store>(ctx: &mut tx_context::TxContext): critbit::CritbitTree<V>
-
- - - -
-Implementation - - -

-public(package) fun new<V: store>(ctx: &mut TxContext): CritbitTree<V> \{
-    CritbitTree<V> \{
-        root: PARTITION_INDEX,
-        internal_nodes: table::new(ctx),
-        leaves: table::new(ctx),
-        min_leaf: PARTITION_INDEX,
-        max_leaf: PARTITION_INDEX,
-        next_internal_node_index: 0,
-        next_leaf_index: 0
-    }
-}
-
- - - -
- - - -## Function `size` - - - -

-public(friend) fun size<V: store>(tree: &critbit::CritbitTree<V>): u64
-
- - - -
-Implementation - - -

-public(package) fun size<V: store>(tree: &CritbitTree<V>): u64 \{
-    table::length(&tree.leaves)
-}
-
- - - -
- - - -## Function `is_empty` - - - -

-public(friend) fun is_empty<V: store>(tree: &critbit::CritbitTree<V>): bool
-
- - - -
-Implementation - - -

-public(package) fun is_empty<V: store>(tree: &CritbitTree<V>): bool \{
-    table::is_empty(&tree.leaves)
-}
-
- - - -
- - - -## Function `min_leaf` - - - -

-public fun min_leaf<V: store>(tree: &critbit::CritbitTree<V>): (u64, u64)
-
- - - -
-Implementation - - -

-public fun min_leaf<V: store>(tree: &CritbitTree<V>): (u64, u64) \{
-    assert!(!is_empty(tree), ELeafNotExist);
-    let min_leaf = table::borrow(&tree.leaves, tree.min_leaf);
-    return (min_leaf.key, tree.min_leaf)
-}
-
- - - -
- - - -## Function `max_leaf` - - - -

-public fun max_leaf<V: store>(tree: &critbit::CritbitTree<V>): (u64, u64)
-
- - - -
-Implementation - - -

-public fun max_leaf<V: store>(tree: &CritbitTree<V>): (u64, u64) \{
-    assert!(!is_empty(tree), ELeafNotExist);
-    let max_leaf = table::borrow(&tree.leaves, tree.max_leaf);
-    return (max_leaf.key, tree.max_leaf)
-}
-
- - - -
- - - -## Function `previous_leaf` - - - -

-public fun previous_leaf<V: store>(tree: &critbit::CritbitTree<V>, key: u64): (u64, u64)
-
- - - -
-Implementation - - -

-public fun previous_leaf<V: store>(tree: &CritbitTree<V>, key: u64): (u64, u64) \{
-    let (_, mut index) = find_leaf(tree, key);
-    assert!(index != PARTITION_INDEX, ELeafNotExist);
-    let mut ptr = MAX_U64 - index;
-    let mut parent = table::borrow(&tree.leaves, index).parent;
-    while (parent != PARTITION_INDEX && is_left_child(tree, parent, ptr))\{
-        ptr = parent;
-        parent = table::borrow(&tree.internal_nodes, ptr).parent;
-    };
-    if(parent == PARTITION_INDEX) \{
-        return (0, PARTITION_INDEX)
-    };
-    index = MAX_U64 - right_most_leaf(tree, table::borrow(&tree.internal_nodes, parent).left_child);
-    let key = table::borrow(&tree.leaves, index).key;
-    return (key, index)
-}
-
- - - -
- - - -## Function `next_leaf` - - - -

-public fun next_leaf<V: store>(tree: &critbit::CritbitTree<V>, key: u64): (u64, u64)
-
- - - -
-Implementation - - -

-public fun next_leaf<V: store>(tree: &CritbitTree<V>, key: u64): (u64, u64) \{
-    let (_, mut index) = find_leaf(tree, key);
-    assert!(index != PARTITION_INDEX, ELeafNotExist);
-    let mut ptr = MAX_U64 - index;
-    let mut parent = table::borrow(&tree.leaves, index).parent;
-    while (parent != PARTITION_INDEX && !is_left_child(tree, parent, ptr))\{
-        ptr = parent;
-        parent = table::borrow(&tree.internal_nodes, ptr).parent;
-    };
-    if(parent == PARTITION_INDEX) \{
-        return (0, PARTITION_INDEX)
-    };
-    index = MAX_U64 - left_most_leaf(tree, table::borrow(&tree.internal_nodes, parent).right_child);
-    let key = table::borrow(&tree.leaves, index).key;
-    return (key, index)
-}
-
- - - -
- - - -## Function `left_most_leaf` - - - -

-fun left_most_leaf<V: store>(tree: &critbit::CritbitTree<V>, root: u64): u64
-
- - - -
-Implementation - - -

-fun left_most_leaf<V: store>(tree: &CritbitTree<V>, root: u64): u64 \{
-    let mut ptr = root;
-    while (ptr < PARTITION_INDEX)\{
-        ptr = table::borrow(& tree.internal_nodes, ptr).left_child;
-    };
-    ptr
-}
-
- - - -
- - - -## Function `right_most_leaf` - - - -

-fun right_most_leaf<V: store>(tree: &critbit::CritbitTree<V>, root: u64): u64
-
- - - -
-Implementation - - -

-fun right_most_leaf<V: store>(tree: &CritbitTree<V>, root: u64): u64 \{
-    let mut ptr = root;
-    while (ptr < PARTITION_INDEX)\{
-        ptr = table::borrow(& tree.internal_nodes, ptr).right_child;
-    };
-    ptr
-}
-
- - - -
- - - -## Function `insert_leaf` - - - -

-public(friend) fun insert_leaf<V: store>(tree: &mut critbit::CritbitTree<V>, key: u64, value: V): u64
-
- - - -
-Implementation - - -

-public(package) fun insert_leaf<V: store>(tree: &mut CritbitTree<V>, key: u64, value: V): u64 \{
-    let new_leaf = Leaf<V>\{
-        key,
-        value,
-        parent: PARTITION_INDEX,
-    };
-    let new_leaf_index = tree.next_leaf_index;
-    tree.next_leaf_index = tree.next_leaf_index + 1;
-    assert!(new_leaf_index < MAX_CAPACITY - 1, EExceedCapacity);
-    table::add(&mut tree.leaves, new_leaf_index, new_leaf);
-
-    let closest_leaf_index = get_closest_leaf_index_by_key(tree, key);
-
-    // Handle the first insertion
-    if (closest_leaf_index == PARTITION_INDEX) \{
-        assert!(new_leaf_index == 0, ETreeNotEmpty);
-        tree.root = MAX_U64 - new_leaf_index;
-        tree.min_leaf = new_leaf_index;
-        tree.max_leaf = new_leaf_index;
-        return 0
-    };
-
-    let closest_key = table::borrow(&tree.leaves, closest_leaf_index).key;
-    assert!(closest_key != key, EKeyAlreadyExist);
-
-    // Note that we reserve count_leading_zeros of form u128 for future use
-    let critbit = 64 - (count_leading_zeros((closest_key ^ key) as u128) - 64);
-    let new_mask = 1u64 << (critbit - 1);
-
-    let new_internal_node= InternalNode \{
-        mask: new_mask,
-        left_child: PARTITION_INDEX,
-        right_child: PARTITION_INDEX,
-        parent: PARTITION_INDEX,
-    };
-    let new_internal_node_index = tree.next_internal_node_index;
-    tree.next_internal_node_index = tree.next_internal_node_index + 1;
-    table::add(&mut tree.internal_nodes, new_internal_node_index, new_internal_node);
-
-    let mut ptr = tree.root;
-    let mut new_internal_node_parent_index = PARTITION_INDEX;
-    // Search position of the new internal node
-    while (ptr < PARTITION_INDEX) \{
-        let internal_node = table::borrow(&tree.internal_nodes, ptr);
-        if (new_mask > internal_node.mask) \{
-            break
-        };
-        new_internal_node_parent_index = ptr;
-        if (key & internal_node.mask == 0) \{
-            ptr = internal_node.left_child;
-        } else \{
-            ptr = internal_node.right_child;
-        };
-    };
-
-    // Update the child info of new internal node's parent
-    if (new_internal_node_parent_index == PARTITION_INDEX)\{
-        // if the new internal node is root
-        tree.root = new_internal_node_index;
-    } else\{
-        // In another case, we update the child field of the new internal node's parent
-        // And the parent field of the new internal node
-        let is_left_child = is_left_child(tree, new_internal_node_parent_index, ptr);
-        update_child(tree, new_internal_node_parent_index, new_internal_node_index, is_left_child);
-    };
-
-    // Finally, update the child field of the new internal node
-    let is_left_child = new_mask & key == 0;
-    update_child(tree, new_internal_node_index, MAX_U64 - new_leaf_index, is_left_child);
-    update_child(tree, new_internal_node_index, ptr, !is_left_child);
-
-    if (table::borrow(&tree.leaves, tree.min_leaf).key > key) \{
-        tree.min_leaf = new_leaf_index;
-    };
-    if (table::borrow(&tree.leaves, tree.max_leaf).key < key) \{
-        tree.max_leaf = new_leaf_index;
-    };
-    new_leaf_index
-}
-
- - - -
- - - -## Function `find_leaf` - - - -

-public fun find_leaf<V: store>(tree: &critbit::CritbitTree<V>, key: u64): (bool, u64)
-
- - - -
-Implementation - - -

-public fun find_leaf<V: store>(tree: & CritbitTree<V>, key: u64): (bool, u64) \{
-    if (is_empty(tree)) \{
-        return (false, PARTITION_INDEX)
-    };
-    let closest_leaf_index = get_closest_leaf_index_by_key(tree, key);
-    let closeset_leaf = table::borrow(&tree.leaves, closest_leaf_index);
-    if (closeset_leaf.key != key)\{
-        return (false, PARTITION_INDEX)
-    } else\{
-        return (true, closest_leaf_index)
-    }
-}
-
- - - -
- - - -## Function `find_closest_key` - - - -

-public(friend) fun find_closest_key<V: store>(tree: &critbit::CritbitTree<V>, key: u64): u64
-
- - - -
-Implementation - - -

-public(package) fun find_closest_key<V: store>(tree: & CritbitTree<V>, key: u64): u64 \{
-    if (is_empty(tree)) \{
-        return 0
-    };
-    let closest_leaf_index = get_closest_leaf_index_by_key(tree, key);
-    let closeset_leaf = table::borrow(&tree.leaves, closest_leaf_index);
-    closeset_leaf.key
-}
-
- - - -
- - - -## Function `remove_leaf_by_index` - - - -

-public(friend) fun remove_leaf_by_index<V: store>(tree: &mut critbit::CritbitTree<V>, index: u64): V
-
- - - -
-Implementation - - -

-public(package) fun remove_leaf_by_index<V: store>(tree: &mut CritbitTree<V>, index: u64): V \{
-    let key = table::borrow(& tree.leaves, index).key;
-    if (tree.min_leaf == index) \{
-        let (_, index) = next_leaf(tree, key);
-        tree.min_leaf = index;
-    };
-    if (tree.max_leaf == index) \{
-        let (_, index) = previous_leaf(tree, key);
-        tree.max_leaf = index;
-    };
-
-    let mut is_left_child_;
-    let Leaf<V> \{key: _, value, parent: removed_leaf_parent_index} = table::remove(&mut tree.leaves, index);
-
-    if (size(tree) == 0) \{
-        tree.root = PARTITION_INDEX;
-        tree.min_leaf = PARTITION_INDEX;
-        tree.max_leaf = PARTITION_INDEX;
-        tree.next_internal_node_index = 0;
-        tree.next_leaf_index = 0;
-    } else \{
-        assert!(removed_leaf_parent_index != PARTITION_INDEX, EIndexOutOfRange);
-        let removed_leaf_parent = table::borrow(&tree.internal_nodes, removed_leaf_parent_index);
-        let removed_leaf_grand_parent_index = removed_leaf_parent.parent;
-
-        // Note that sibling of the removed leaf can be a leaf or an internal node
-        is_left_child_ = is_left_child(tree, removed_leaf_parent_index, MAX_U64 - index);
-        let sibling_index = if (is_left_child_) \{ removed_leaf_parent.right_child }
-        else \{ removed_leaf_parent.left_child };
-
-        if (removed_leaf_grand_parent_index == PARTITION_INDEX) \{
-            // Parent of the removed leaf is the tree root
-            // Update the parent of the sibling node and and set sibling as the tree root
-            if (sibling_index < PARTITION_INDEX) \{
-                // sibling is an internal node
-                table::borrow_mut(&mut tree.internal_nodes, sibling_index).parent = PARTITION_INDEX;
-            } else\{
-                // sibling is a leaf
-                table::borrow_mut(&mut tree.leaves, MAX_U64 - sibling_index).parent = PARTITION_INDEX;
-            };
-            tree.root = sibling_index;
-        } else \{
-            // grand parent of the removed leaf is a internal node
-            // set sibling as the child of the grand parent of the removed leaf
-            is_left_child_ = is_left_child(tree, removed_leaf_grand_parent_index, removed_leaf_parent_index);
-            update_child(tree, removed_leaf_grand_parent_index, sibling_index, is_left_child_);
-        };
-        table::remove(&mut tree.internal_nodes, removed_leaf_parent_index);
-    };
-    value
-}
-
- - - -
- - - -## Function `borrow_mut_leaf_by_index` - - - -

-public(friend) fun borrow_mut_leaf_by_index<V: store>(tree: &mut critbit::CritbitTree<V>, index: u64): &mut V
-
- - - -
-Implementation - - -

-public(package) fun borrow_mut_leaf_by_index<V: store>(tree: &mut CritbitTree<V>, index: u64): &mut V \{
-    let entry = table::borrow_mut(&mut tree.leaves, index);
-    &mut entry.value
-}
-
- - - -
- - - -## Function `borrow_leaf_by_index` - - - -

-public fun borrow_leaf_by_index<V: store>(tree: &critbit::CritbitTree<V>, index: u64): &V
-
- - - -
-Implementation - - -

-public fun borrow_leaf_by_index<V: store>(tree: & CritbitTree<V>, index: u64): &V \{
-    let entry = table::borrow(&tree.leaves, index);
-    &entry.value
-}
-
- - - -
- - - -## Function `borrow_leaf_by_key` - - - -

-public fun borrow_leaf_by_key<V: store>(tree: &critbit::CritbitTree<V>, key: u64): &V
-
- - - -
-Implementation - - -

-public fun borrow_leaf_by_key<V: store>(tree: & CritbitTree<V>, key: u64): &V \{
-    let (is_exist, index) = find_leaf(tree, key);
-    assert!(is_exist, ELeafNotExist);
-    borrow_leaf_by_index(tree, index)
-}
-
- - - -
- - - -## Function `drop` - - - -

-public(friend) fun drop<V: drop, store>(tree: critbit::CritbitTree<V>)
-
- - - -
-Implementation - - -

-public(package) fun drop<V: store + drop>(tree: CritbitTree<V>) \{
-    let CritbitTree<V> \{
-        root: _,
-        internal_nodes,
-        leaves,
-        min_leaf: _,
-        max_leaf: _,
-        next_internal_node_index: _,
-        next_leaf_index: _,
-
-    } = tree;
-    table::drop(internal_nodes);
-    table::drop(leaves);
-}
-
- - - -
- - - -## Function `destroy_empty` - - - -

-public(friend) fun destroy_empty<V: store>(tree: critbit::CritbitTree<V>)
-
- - - -
-Implementation - - -

-public(package) fun destroy_empty<V: store>(tree: CritbitTree<V>) \{
-    assert!(table::length(&tree.leaves) == 0, 0);
-
-    let CritbitTree<V> \{
-        root: _,
-        leaves,
-        internal_nodes,
-        min_leaf: _,
-        max_leaf: _,
-        next_internal_node_index: _,
-        next_leaf_index: _
-    } = tree;
-
-    table::destroy_empty(leaves);
-    table::destroy_empty(internal_nodes);
-}
-
- - - -
- - - -## Function `get_closest_leaf_index_by_key` - - - -

-fun get_closest_leaf_index_by_key<V: store>(tree: &critbit::CritbitTree<V>, key: u64): u64
-
- - - -
-Implementation - - -

-fun get_closest_leaf_index_by_key<V: store>(tree: &CritbitTree<V>, key: u64): u64 \{
-    let mut ptr = tree.root;
-    // if tree is empty, return the patrition index
-    if(ptr == PARTITION_INDEX) return PARTITION_INDEX;
-    while (ptr < PARTITION_INDEX)\{
-        let node = table::borrow(&tree.internal_nodes, ptr);
-        if (key & node.mask == 0)\{
-            ptr = node.left_child;
-        } else \{
-            ptr = node.right_child;
-        }
-    };
-    return (MAX_U64 - ptr)
-}
-
- - - -
- - - -## Function `update_child` - - - -

-fun update_child<V: store>(tree: &mut critbit::CritbitTree<V>, parent_index: u64, new_child: u64, is_left_child: bool)
-
- - - -
-Implementation - - -

-fun update_child<V: store>(tree: &mut CritbitTree<V>, parent_index: u64, new_child: u64, is_left_child: bool) \{
-    assert!(parent_index != PARTITION_INDEX, ENullParent);
-    if (is_left_child) \{
-        table::borrow_mut(&mut tree.internal_nodes, parent_index).left_child = new_child;
-    } else\{
-        table::borrow_mut(&mut tree.internal_nodes, parent_index).right_child = new_child;
-    };
-    if (new_child > PARTITION_INDEX) \{
-        table::borrow_mut(&mut tree.leaves, MAX_U64 - new_child).parent = parent_index;
-    } else \{
-        table::borrow_mut(&mut tree.internal_nodes, new_child).parent = parent_index;
-    }
-}
-
- - - -
- - - -## Function `is_left_child` - - - -

-fun is_left_child<V: store>(tree: &critbit::CritbitTree<V>, parent_index: u64, index: u64): bool
-
- - - -
-Implementation - - -

-fun is_left_child<V: store>(tree: &CritbitTree<V>, parent_index: u64, index: u64): bool \{
-    table::borrow(&tree.internal_nodes, parent_index).left_child == index
-}
-
- - - -
diff --git a/crates/iota-framework/docs/deepbook/custodian.mdx b/crates/iota-framework/docs/deepbook/custodian.mdx deleted file mode 100644 index d8bd9667778..00000000000 --- a/crates/iota-framework/docs/deepbook/custodian.mdx +++ /dev/null @@ -1,548 +0,0 @@ ---- -title: Module `0xdee9::custodian` ---- -import Link from '@docusaurus/Link'; - - - - -- [Struct `Account`](#0xdee9_custodian_Account) -- [Resource `AccountCap`](#0xdee9_custodian_AccountCap) -- [Resource `Custodian`](#0xdee9_custodian_Custodian) -- [Function `mint_account_cap`](#0xdee9_custodian_mint_account_cap) -- [Function `account_balance`](#0xdee9_custodian_account_balance) -- [Function `new`](#0xdee9_custodian_new) -- [Function `withdraw_asset`](#0xdee9_custodian_withdraw_asset) -- [Function `increase_user_available_balance`](#0xdee9_custodian_increase_user_available_balance) -- [Function `decrease_user_available_balance`](#0xdee9_custodian_decrease_user_available_balance) -- [Function `increase_user_locked_balance`](#0xdee9_custodian_increase_user_locked_balance) -- [Function `decrease_user_locked_balance`](#0xdee9_custodian_decrease_user_locked_balance) -- [Function `lock_balance`](#0xdee9_custodian_lock_balance) -- [Function `unlock_balance`](#0xdee9_custodian_unlock_balance) -- [Function `account_available_balance`](#0xdee9_custodian_account_available_balance) -- [Function `account_locked_balance`](#0xdee9_custodian_account_locked_balance) -- [Function `borrow_mut_account_balance`](#0xdee9_custodian_borrow_mut_account_balance) - - -

-use 0x2::balance;
-use 0x2::coin;
-use 0x2::object;
-use 0x2::table;
-use 0x2::tx_context;
-
- - - - - -## Struct `Account` - - - -

-struct Account<T> has store
-
- - - -
-Fields - - -
-
- -available_balance: balance::Balance<T> -
-
- -
-
- -locked_balance: balance::Balance<T> -
-
- -
-
- - -
- - - -## Resource `AccountCap` - - - -

-struct AccountCap has store, key
-
- - - -
-Fields - - -
-
- -id: object::UID -
-
- -
-
- - -
- - - -## Resource `Custodian` - - - -

-struct Custodian<T> has store, key
-
- - - -
-Fields - - -
-
- -id: object::UID -
-
- -
-
- -account_balances: table::Table<object::ID, custodian::Account<T>> -
-
- Map from an AccountCap object ID to an Account object -
-
- - -
- - - -## Function `mint_account_cap` - -Create an -AccountCap that can be used across all DeepBook pool - - -

-public fun mint_account_cap(ctx: &mut tx_context::TxContext): custodian::AccountCap
-
- - - -
-Implementation - - -

-public fun mint_account_cap(ctx: &mut TxContext): AccountCap \{
-    AccountCap \{ id: object::new(ctx) }
-}
-
- - - -
- - - -## Function `account_balance` - - - -

-public(friend) fun account_balance<Asset>(custodian: &custodian::Custodian<Asset>, user: object::ID): (u64, u64)
-
- - - -
-Implementation - - -

-public(package) fun account_balance<Asset>(
-    custodian: &Custodian<Asset>,
-    user: ID
-): (u64, u64) \{
-    // if custodian account is not created yet, directly return (0, 0) rather than abort
-    if (!table::contains(&custodian.account_balances, user)) \{
-        return (0, 0)
-    };
-    let account_balances = table::borrow(&custodian.account_balances, user);
-    let avail_balance = balance::value(&account_balances.available_balance);
-    let locked_balance = balance::value(&account_balances.locked_balance);
-    (avail_balance, locked_balance)
-}
-
- - - -
- - - -## Function `new` - - - -

-public(friend) fun new<T>(ctx: &mut tx_context::TxContext): custodian::Custodian<T>
-
- - - -
-Implementation - - -

-public(package) fun new<T>(ctx: &mut TxContext): Custodian<T> \{
-    Custodian<T> \{
-        id: object::new(ctx),
-        account_balances: table::new(ctx),
-    }
-}
-
- - - -
- - - -## Function `withdraw_asset` - - - -

-public(friend) fun withdraw_asset<Asset>(custodian: &mut custodian::Custodian<Asset>, quantity: u64, account_cap: &custodian::AccountCap, ctx: &mut tx_context::TxContext): coin::Coin<Asset>
-
- - - -
-Implementation - - -

-public(package) fun withdraw_asset<Asset>(
-    custodian: &mut Custodian<Asset>,
-    quantity: u64,
-    account_cap: &AccountCap,
-    ctx: &mut TxContext
-): Coin<Asset> \{
-    coin::from_balance(decrease_user_available_balance<Asset>(custodian, account_cap, quantity), ctx)
-}
-
- - - -
- - - -## Function `increase_user_available_balance` - - - -

-public(friend) fun increase_user_available_balance<T>(custodian: &mut custodian::Custodian<T>, user: object::ID, quantity: balance::Balance<T>)
-
- - - -
-Implementation - - -

-public(package) fun increase_user_available_balance<T>(
-    custodian: &mut Custodian<T>,
-    user: ID,
-    quantity: Balance<T>,
-) \{
-    let account = borrow_mut_account_balance<T>(custodian, user);
-    balance::join(&mut account.available_balance, quantity);
-}
-
- - - -
- - - -## Function `decrease_user_available_balance` - - - -

-public(friend) fun decrease_user_available_balance<T>(custodian: &mut custodian::Custodian<T>, account_cap: &custodian::AccountCap, quantity: u64): balance::Balance<T>
-
- - - -
-Implementation - - -

-public(package) fun decrease_user_available_balance<T>(
-    custodian: &mut Custodian<T>,
-    account_cap: &AccountCap,
-    quantity: u64,
-): Balance<T> \{
-    let account = borrow_mut_account_balance<T>(custodian, object::uid_to_inner(&account_cap.id));
-    balance::split(&mut account.available_balance, quantity)
-}
-
- - - -
- - - -## Function `increase_user_locked_balance` - - - -

-public(friend) fun increase_user_locked_balance<T>(custodian: &mut custodian::Custodian<T>, account_cap: &custodian::AccountCap, quantity: balance::Balance<T>)
-
- - - -
-Implementation - - -

-public(package) fun increase_user_locked_balance<T>(
-    custodian: &mut Custodian<T>,
-    account_cap: &AccountCap,
-    quantity: Balance<T>,
-) \{
-    let account = borrow_mut_account_balance<T>(custodian, object::uid_to_inner(&account_cap.id));
-    balance::join(&mut account.locked_balance, quantity);
-}
-
- - - -
- - - -## Function `decrease_user_locked_balance` - - - -

-public(friend) fun decrease_user_locked_balance<T>(custodian: &mut custodian::Custodian<T>, user: object::ID, quantity: u64): balance::Balance<T>
-
- - - -
-Implementation - - -

-public(package) fun decrease_user_locked_balance<T>(
-    custodian: &mut Custodian<T>,
-    user: ID,
-    quantity: u64,
-): Balance<T> \{
-    let account = borrow_mut_account_balance<T>(custodian, user);
-    split(&mut account.locked_balance, quantity)
-}
-
- - - -
- - - -## Function `lock_balance` - -Move -quantity from the unlocked balance of -user to the locked balance of -user - - -

-public(friend) fun lock_balance<T>(custodian: &mut custodian::Custodian<T>, account_cap: &custodian::AccountCap, quantity: u64)
-
- - - -
-Implementation - - -

-public(package) fun lock_balance<T>(
-    custodian: &mut Custodian<T>,
-    account_cap: &AccountCap,
-    quantity: u64,
-) \{
-    let to_lock = decrease_user_available_balance(custodian, account_cap, quantity);
-    increase_user_locked_balance(custodian, account_cap, to_lock);
-}
-
- - - -
- - - -## Function `unlock_balance` - -Move -quantity from the locked balance of -user to the unlocked balacne of -user - - -

-public(friend) fun unlock_balance<T>(custodian: &mut custodian::Custodian<T>, user: object::ID, quantity: u64)
-
- - - -
-Implementation - - -

-public(package) fun unlock_balance<T>(
-    custodian: &mut Custodian<T>,
-    user: ID,
-    quantity: u64,
-) \{
-    let locked_balance = decrease_user_locked_balance<T>(custodian, user, quantity);
-    increase_user_available_balance<T>(custodian, user, locked_balance)
-}
-
- - - -
- - - -## Function `account_available_balance` - - - -

-public(friend) fun account_available_balance<T>(custodian: &custodian::Custodian<T>, user: object::ID): u64
-
- - - -
-Implementation - - -

-public(package) fun account_available_balance<T>(
-    custodian: &Custodian<T>,
-    user: ID,
-): u64 \{
-    balance::value(&table::borrow(&custodian.account_balances, user).available_balance)
-}
-
- - - -
- - - -## Function `account_locked_balance` - - - -

-public(friend) fun account_locked_balance<T>(custodian: &custodian::Custodian<T>, user: object::ID): u64
-
- - - -
-Implementation - - -

-public(package) fun account_locked_balance<T>(
-    custodian: &Custodian<T>,
-    user: ID,
-): u64 \{
-    balance::value(&table::borrow(&custodian.account_balances, user).locked_balance)
-}
-
- - - -
- - - -## Function `borrow_mut_account_balance` - - - -

-fun borrow_mut_account_balance<T>(custodian: &mut custodian::Custodian<T>, user: object::ID): &mut custodian::Account<T>
-
- - - -
-Implementation - - -

-fun borrow_mut_account_balance<T>(
-    custodian: &mut Custodian<T>,
-    user: ID,
-): &mut Account<T> \{
-    if (!table::contains(&custodian.account_balances, user)) \{
-        table::add(
-            &mut custodian.account_balances,
-            user,
-            Account \{ available_balance: balance::zero(), locked_balance: balance::zero() }
-        );
-    };
-    table::borrow_mut(&mut custodian.account_balances, user)
-}
-
- - - -
diff --git a/crates/iota-framework/docs/deepbook/custodian_v2.mdx b/crates/iota-framework/docs/deepbook/custodian_v2.mdx deleted file mode 100644 index 997fb9f5210..00000000000 --- a/crates/iota-framework/docs/deepbook/custodian_v2.mdx +++ /dev/null @@ -1,680 +0,0 @@ ---- -title: Module `0xdee9::custodian_v2` ---- -import Link from '@docusaurus/Link'; - - - - -- [Struct `Account`](#0xdee9_custodian_v2_Account) -- [Resource `AccountCap`](#0xdee9_custodian_v2_AccountCap) -- [Resource `Custodian`](#0xdee9_custodian_v2_Custodian) -- [Constants](#@Constants_0) -- [Function `mint_account_cap`](#0xdee9_custodian_v2_mint_account_cap) -- [Function `create_child_account_cap`](#0xdee9_custodian_v2_create_child_account_cap) -- [Function `delete_account_cap`](#0xdee9_custodian_v2_delete_account_cap) -- [Function `account_owner`](#0xdee9_custodian_v2_account_owner) -- [Function `account_balance`](#0xdee9_custodian_v2_account_balance) -- [Function `new`](#0xdee9_custodian_v2_new) -- [Function `withdraw_asset`](#0xdee9_custodian_v2_withdraw_asset) -- [Function `increase_user_available_balance`](#0xdee9_custodian_v2_increase_user_available_balance) -- [Function `decrease_user_available_balance`](#0xdee9_custodian_v2_decrease_user_available_balance) -- [Function `increase_user_locked_balance`](#0xdee9_custodian_v2_increase_user_locked_balance) -- [Function `decrease_user_locked_balance`](#0xdee9_custodian_v2_decrease_user_locked_balance) -- [Function `lock_balance`](#0xdee9_custodian_v2_lock_balance) -- [Function `unlock_balance`](#0xdee9_custodian_v2_unlock_balance) -- [Function `account_available_balance`](#0xdee9_custodian_v2_account_available_balance) -- [Function `account_locked_balance`](#0xdee9_custodian_v2_account_locked_balance) -- [Function `borrow_mut_account_balance`](#0xdee9_custodian_v2_borrow_mut_account_balance) - - -

-use 0x2::balance;
-use 0x2::coin;
-use 0x2::object;
-use 0x2::table;
-use 0x2::tx_context;
-
- - - - - -## Struct `Account` - - - -

-struct Account<T> has store
-
- - - -
-Fields - - -
-
- -available_balance: balance::Balance<T> -
-
- -
-
- -locked_balance: balance::Balance<T> -
-
- -
-
- - -
- - - -## Resource `AccountCap` - -Capability granting permission to access an entry in -Custodian.account_balances. -Calling -mint_account_cap creates an "admin account cap" such that id == owner with -the permission to both access funds and create new -AccountCaps. -Calling -create_child_account_cap creates a "child account cap" such that id != owner -that can access funds, but cannot create new -AccountCaps. - - -

-struct AccountCap has store, key
-
- - - -
-Fields - - -
-
- -id: object::UID -
-
- -
-
- -owner: address -
-
- The owner of this AccountCap. Note: this is - derived from an object ID, not a user address -
-
- - -
- - - -## Resource `Custodian` - - - -

-struct Custodian<T> has store, key
-
- - - -
-Fields - - -
-
- -id: object::UID -
-
- -
-
- -account_balances: table::Table<address, custodian_v2::Account<T>> -
-
- Map from the owner address of AccountCap object to an Account object -
-
- - -
- - - -## Constants - - - - - - -

-const EAdminAccountCapRequired: u64 = 2;
-
- - - - - -## Function `mint_account_cap` - -Create an admin -AccountCap that can be used across all DeepBook pools, and has -the permission to create new -AccountCaps that can access the same source of funds - - -

-public(friend) fun mint_account_cap(ctx: &mut tx_context::TxContext): custodian_v2::AccountCap
-
- - - -
-Implementation - - -

-public(package) fun mint_account_cap(ctx: &mut TxContext): AccountCap \{
-    let id = object::new(ctx);
-    let owner = object::uid_to_address(&id);
-    AccountCap \{ id, owner }
-}
-
- - - -
- - - -## Function `create_child_account_cap` - -Create a "child account cap" such that id != owner -that can access funds, but cannot create new -AccountCaps. - - -

-public fun create_child_account_cap(admin_account_cap: &custodian_v2::AccountCap, ctx: &mut tx_context::TxContext): custodian_v2::AccountCap
-
- - - -
-Implementation - - -

-public fun create_child_account_cap(admin_account_cap: &AccountCap, ctx: &mut TxContext): AccountCap \{
-    // Only the admin account cap can create new account caps
-    assert!(object::uid_to_address(&admin_account_cap.id) == admin_account_cap.owner, EAdminAccountCapRequired);
-
-    AccountCap \{
-        id: object::new(ctx),
-        owner: admin_account_cap.owner
-    }
-}
-
- - - -
- - - -## Function `delete_account_cap` - -Destroy the given -account_cap object - - -

-public fun delete_account_cap(account_cap: custodian_v2::AccountCap)
-
- - - -
-Implementation - - -

-public fun delete_account_cap(account_cap: AccountCap) \{
-    let AccountCap \{ id, owner: _ } = account_cap;
-    object::delete(id)
-}
-
- - - -
- - - -## Function `account_owner` - -Return the owner of an AccountCap - - -

-public fun account_owner(account_cap: &custodian_v2::AccountCap): address
-
- - - -
-Implementation - - -

-public fun account_owner(account_cap: &AccountCap): address \{
-    account_cap.owner
-}
-
- - - -
- - - -## Function `account_balance` - - - -

-public(friend) fun account_balance<Asset>(custodian: &custodian_v2::Custodian<Asset>, owner: address): (u64, u64)
-
- - - -
-Implementation - - -

-public(package) fun account_balance<Asset>(
-    custodian: &Custodian<Asset>,
-    owner: address
-): (u64, u64) \{
-    // if custodian account is not created yet, directly return (0, 0) rather than abort
-    if (!table::contains(&custodian.account_balances, owner)) \{
-        return (0, 0)
-    };
-    let account_balances = table::borrow(&custodian.account_balances, owner);
-    let avail_balance = balance::value(&account_balances.available_balance);
-    let locked_balance = balance::value(&account_balances.locked_balance);
-    (avail_balance, locked_balance)
-}
-
- - - -
- - - -## Function `new` - - - -

-public(friend) fun new<T>(ctx: &mut tx_context::TxContext): custodian_v2::Custodian<T>
-
- - - -
-Implementation - - -

-public(package) fun new<T>(ctx: &mut TxContext): Custodian<T> \{
-    Custodian<T> \{
-        id: object::new(ctx),
-        account_balances: table::new(ctx),
-    }
-}
-
- - - -
- - - -## Function `withdraw_asset` - - - -

-public(friend) fun withdraw_asset<Asset>(custodian: &mut custodian_v2::Custodian<Asset>, quantity: u64, account_cap: &custodian_v2::AccountCap, ctx: &mut tx_context::TxContext): coin::Coin<Asset>
-
- - - -
-Implementation - - -

-public(package) fun withdraw_asset<Asset>(
-    custodian: &mut Custodian<Asset>,
-    quantity: u64,
-    account_cap: &AccountCap,
-    ctx: &mut TxContext
-): Coin<Asset> \{
-    coin::from_balance(decrease_user_available_balance<Asset>(custodian, account_cap, quantity), ctx)
-}
-
- - - -
- - - -## Function `increase_user_available_balance` - - - -

-public(friend) fun increase_user_available_balance<T>(custodian: &mut custodian_v2::Custodian<T>, owner: address, quantity: balance::Balance<T>)
-
- - - -
-Implementation - - -

-public(package) fun increase_user_available_balance<T>(
-    custodian: &mut Custodian<T>,
-    owner: address,
-    quantity: Balance<T>,
-) \{
-    let account = borrow_mut_account_balance<T>(custodian, owner);
-    balance::join(&mut account.available_balance, quantity);
-}
-
- - - -
- - - -## Function `decrease_user_available_balance` - - - -

-public(friend) fun decrease_user_available_balance<T>(custodian: &mut custodian_v2::Custodian<T>, account_cap: &custodian_v2::AccountCap, quantity: u64): balance::Balance<T>
-
- - - -
-Implementation - - -

-public(package) fun decrease_user_available_balance<T>(
-    custodian: &mut Custodian<T>,
-    account_cap: &AccountCap,
-    quantity: u64,
-): Balance<T> \{
-    let account = borrow_mut_account_balance<T>(custodian, account_cap.owner);
-    balance::split(&mut account.available_balance, quantity)
-}
-
- - - -
- - - -## Function `increase_user_locked_balance` - - - -

-public(friend) fun increase_user_locked_balance<T>(custodian: &mut custodian_v2::Custodian<T>, account_cap: &custodian_v2::AccountCap, quantity: balance::Balance<T>)
-
- - - -
-Implementation - - -

-public(package) fun increase_user_locked_balance<T>(
-    custodian: &mut Custodian<T>,
-    account_cap: &AccountCap,
-    quantity: Balance<T>,
-) \{
-    let account = borrow_mut_account_balance<T>(custodian, account_cap.owner);
-    balance::join(&mut account.locked_balance, quantity);
-}
-
- - - -
- - - -## Function `decrease_user_locked_balance` - - - -

-public(friend) fun decrease_user_locked_balance<T>(custodian: &mut custodian_v2::Custodian<T>, owner: address, quantity: u64): balance::Balance<T>
-
- - - -
-Implementation - - -

-public(package) fun decrease_user_locked_balance<T>(
-    custodian: &mut Custodian<T>,
-    owner: address,
-    quantity: u64,
-): Balance<T> \{
-    let account = borrow_mut_account_balance<T>(custodian, owner);
-    split(&mut account.locked_balance, quantity)
-}
-
- - - -
- - - -## Function `lock_balance` - -Move -quantity from the unlocked balance of -user to the locked balance of -user - - -

-public(friend) fun lock_balance<T>(custodian: &mut custodian_v2::Custodian<T>, account_cap: &custodian_v2::AccountCap, quantity: u64)
-
- - - -
-Implementation - - -

-public(package) fun lock_balance<T>(
-    custodian: &mut Custodian<T>,
-    account_cap: &AccountCap,
-    quantity: u64,
-) \{
-    let to_lock = decrease_user_available_balance(custodian, account_cap, quantity);
-    increase_user_locked_balance(custodian, account_cap, to_lock);
-}
-
- - - -
- - - -## Function `unlock_balance` - -Move -quantity from the locked balance of -user to the unlocked balance of -user - - -

-public(friend) fun unlock_balance<T>(custodian: &mut custodian_v2::Custodian<T>, owner: address, quantity: u64)
-
- - - -
-Implementation - - -

-public(package) fun unlock_balance<T>(
-    custodian: &mut Custodian<T>,
-    owner: address,
-    quantity: u64,
-) \{
-    let locked_balance = decrease_user_locked_balance<T>(custodian, owner, quantity);
-    increase_user_available_balance<T>(custodian, owner, locked_balance)
-}
-
- - - -
- - - -## Function `account_available_balance` - - - -

-public(friend) fun account_available_balance<T>(custodian: &custodian_v2::Custodian<T>, owner: address): u64
-
- - - -
-Implementation - - -

-public(package) fun account_available_balance<T>(
-    custodian: &Custodian<T>,
-    owner: address,
-): u64 \{
-    balance::value(&table::borrow(&custodian.account_balances, owner).available_balance)
-}
-
- - - -
- - - -## Function `account_locked_balance` - - - -

-public(friend) fun account_locked_balance<T>(custodian: &custodian_v2::Custodian<T>, owner: address): u64
-
- - - -
-Implementation - - -

-public(package) fun account_locked_balance<T>(
-    custodian: &Custodian<T>,
-    owner: address,
-): u64 \{
-    balance::value(&table::borrow(&custodian.account_balances, owner).locked_balance)
-}
-
- - - -
- - - -## Function `borrow_mut_account_balance` - - - -

-fun borrow_mut_account_balance<T>(custodian: &mut custodian_v2::Custodian<T>, owner: address): &mut custodian_v2::Account<T>
-
- - - -
-Implementation - - -

-fun borrow_mut_account_balance<T>(
-    custodian: &mut Custodian<T>,
-    owner: address,
-): &mut Account<T> \{
-    if (!table::contains(&custodian.account_balances, owner)) \{
-        table::add(
-            &mut custodian.account_balances,
-            owner,
-            Account \{ available_balance: balance::zero(), locked_balance: balance::zero() }
-        );
-    };
-    table::borrow_mut(&mut custodian.account_balances, owner)
-}
-
- - - -
diff --git a/crates/iota-framework/docs/deepbook/math.mdx b/crates/iota-framework/docs/deepbook/math.mdx deleted file mode 100644 index 63251f8397a..00000000000 --- a/crates/iota-framework/docs/deepbook/math.mdx +++ /dev/null @@ -1,322 +0,0 @@ ---- -title: Module `0xdee9::math` ---- -import Link from '@docusaurus/Link'; - - - - -- [Constants](#@Constants_0) -- [Function `unsafe_mul`](#0xdee9_math_unsafe_mul) -- [Function `unsafe_mul_round`](#0xdee9_math_unsafe_mul_round) -- [Function `mul`](#0xdee9_math_mul) -- [Function `mul_round`](#0xdee9_math_mul_round) -- [Function `unsafe_div`](#0xdee9_math_unsafe_div) -- [Function `unsafe_div_round`](#0xdee9_math_unsafe_div_round) -- [Function `div_round`](#0xdee9_math_div_round) -- [Function `count_leading_zeros`](#0xdee9_math_count_leading_zeros) - - -

-
- - - - - -## Constants - - - - - - -

-const EUnderflow: u64 = 1;
-
- - - - - -scaling setting for float - - -

-const FLOAT_SCALING: u64 = 1000000000;
-
- - - - - - - -

-const FLOAT_SCALING_U128: u128 = 1000000000;
-
- - - - - -## Function `unsafe_mul` - - - -

-public(friend) fun unsafe_mul(x: u64, y: u64): u64
-
- - - -
-Implementation - - -

-public(package) fun unsafe_mul(x: u64, y: u64): u64 \{
-    let (_, result) = unsafe_mul_round(x, y);
-    result
-}
-
- - - -
- - - -## Function `unsafe_mul_round` - - - -

-public(friend) fun unsafe_mul_round(x: u64, y: u64): (bool, u64)
-
- - - -
-Implementation - - -

-public(package) fun unsafe_mul_round(x: u64, y: u64): (bool, u64) \{
-    let x = x as u128;
-    let y = y as u128;
-    let mut is_round_down = true;
-    if ((x * y) % FLOAT_SCALING_U128 == 0) is_round_down = false;
-    (is_round_down, (x * y / FLOAT_SCALING_U128) as u64)
-}
-
- - - -
- - - -## Function `mul` - - - -

-public fun mul(x: u64, y: u64): u64
-
- - - -
-Implementation - - -

-public fun mul(x: u64, y: u64): u64 \{
-    let (_, result) = unsafe_mul_round(x, y);
-    assert!(result > 0, EUnderflow);
-    result
-}
-
- - - -
- - - -## Function `mul_round` - - - -

-public fun mul_round(x: u64, y: u64): (bool, u64)
-
- - - -
-Implementation - - -

-public fun mul_round(x: u64, y: u64): (bool, u64) \{
-    let (is_round_down, result) = unsafe_mul_round(x, y);
-    assert!(result > 0, EUnderflow);
-    (is_round_down, result)
-}
-
- - - -
- - - -## Function `unsafe_div` - - - -

-public(friend) fun unsafe_div(x: u64, y: u64): u64
-
- - - -
-Implementation - - -

-public(package) fun unsafe_div(x: u64, y: u64): u64 \{
-    let (_, result) = unsafe_div_round(x, y);
-    result
-}
-
- - - -
- - - -## Function `unsafe_div_round` - - - -

-public(friend) fun unsafe_div_round(x: u64, y: u64): (bool, u64)
-
- - - -
-Implementation - - -

-public(package) fun unsafe_div_round(x: u64, y: u64): (bool, u64) \{
-    let x = x as u128;
-    let y = y as u128;
-    let mut is_round_down = true;
-    if ((x * (FLOAT_SCALING as u128) % y) == 0) is_round_down = false;
-    (is_round_down, (x * (FLOAT_SCALING as u128) / y) as u64)
-}
-
- - - -
- - - -## Function `div_round` - - - -

-public fun div_round(x: u64, y: u64): (bool, u64)
-
- - - -
-Implementation - - -

-public fun div_round(x: u64, y: u64): (bool, u64) \{
-    let (is_round_down, result) = unsafe_div_round(x, y);
-    assert!(result > 0, EUnderflow);
-    (is_round_down, result)
-}
-
- - - -
- - - -## Function `count_leading_zeros` - - - -

-public(friend) fun count_leading_zeros(x: u128): u8
-
- - - -
-Implementation - - -

-public(package) fun count_leading_zeros(mut x: u128): u8 \{
-    if (x == 0) \{
-        128
-    } else \{
-        let mut n: u8 = 0;
-        if (x & 0xFFFFFFFFFFFFFFFF0000000000000000 == 0) \{
-            // x's higher 64 is all zero, shift the lower part over
-            x = x << 64;
-            n = n + 64;
-        };
-        if (x & 0xFFFFFFFF000000000000000000000000 == 0) \{
-            // x's higher 32 is all zero, shift the lower part over
-            x = x << 32;
-            n = n + 32;
-        };
-        if (x & 0xFFFF0000000000000000000000000000 == 0) \{
-            // x's higher 16 is all zero, shift the lower part over
-            x = x << 16;
-            n = n + 16;
-        };
-        if (x & 0xFF000000000000000000000000000000 == 0) \{
-            // x's higher 8 is all zero, shift the lower part over
-            x = x << 8;
-            n = n + 8;
-        };
-        if (x & 0xF0000000000000000000000000000000 == 0) \{
-            // x's higher 4 is all zero, shift the lower part over
-            x = x << 4;
-            n = n + 4;
-        };
-        if (x & 0xC0000000000000000000000000000000 == 0) \{
-            // x's higher 2 is all zero, shift the lower part over
-            x = x << 2;
-            n = n + 2;
-        };
-        if (x & 0x80000000000000000000000000000000 == 0) \{
-            n = n + 1;
-        };
-
-        n
-    }
-}
-
- - - -
diff --git a/crates/iota-framework/docs/deepbook/order_query.mdx b/crates/iota-framework/docs/deepbook/order_query.mdx deleted file mode 100644 index 147788d2f31..00000000000 --- a/crates/iota-framework/docs/deepbook/order_query.mdx +++ /dev/null @@ -1,470 +0,0 @@ ---- -title: Module `0xdee9::order_query` ---- -import Link from '@docusaurus/Link'; - - - - -- [Struct `OrderPage`](#0xdee9_order_query_OrderPage) -- [Constants](#@Constants_0) -- [Function `iter_bids`](#0xdee9_order_query_iter_bids) -- [Function `iter_asks`](#0xdee9_order_query_iter_asks) -- [Function `iter_ticks_internal`](#0xdee9_order_query_iter_ticks_internal) -- [Function `orders`](#0xdee9_order_query_orders) -- [Function `has_next_page`](#0xdee9_order_query_has_next_page) -- [Function `next_tick_level`](#0xdee9_order_query_next_tick_level) -- [Function `next_order_id`](#0xdee9_order_query_next_order_id) -- [Function `order_id`](#0xdee9_order_query_order_id) -- [Function `tick_level`](#0xdee9_order_query_tick_level) - - -

-use 0x1::option;
-use 0x2::linked_table;
-use 0xdee9::clob_v2;
-use 0xdee9::critbit;
-
- - - - - -## Struct `OrderPage` - - - -

-struct OrderPage has drop
-
- - - -
-Fields - - -
-
- -orders: vector<clob_v2::Order> -
-
- -
-
- -has_next_page: bool -
-
- -
-
- -next_tick_level: option::Option<u64> -
-
- -
-
- -next_order_id: option::Option<u64> -
-
- -
-
- - -
- - - -## Constants - - - - - - -

-const PAGE_LIMIT: u64 = 100;
-
- - - - - -## Function `iter_bids` - - - -

-public fun iter_bids<T1, T2>(pool: &clob_v2::Pool<T1, T2>, start_tick_level: option::Option<u64>, start_order_id: option::Option<u64>, min_expire_timestamp: option::Option<u64>, max_id: option::Option<u64>, ascending: bool): order_query::OrderPage
-
- - - -
-Implementation - - -

-public fun iter_bids<T1, T2>(
-    pool: &Pool<T1, T2>,
-    // tick level to start from
-    start_tick_level: Option<u64>,
-    // order id within that tick level to start from
-    start_order_id: Option<u64>,
-    // if provided, do not include orders with an expire timestamp less than the provided value (expired order),
-    // value is in microseconds
-    min_expire_timestamp: Option<u64>,
-    // do not show orders with an ID larger than max_id--
-    // i.e., orders added later than this one
-    max_id: Option<u64>,
-    // if true, the orders are returned in ascending tick level.
-    ascending: bool,
-): OrderPage \{
-    let bids = clob_v2::bids(pool);
-    let mut orders = iter_ticks_internal(
-        bids,
-        start_tick_level,
-        start_order_id,
-        min_expire_timestamp,
-        max_id,
-        ascending
-    );
-    let (orders, has_next_page, next_tick_level, next_order_id) = if (vector::length(&orders) > PAGE_LIMIT) \{
-        let last_order = vector::pop_back(&mut orders);
-        (orders, true, some(clob_v2::tick_level(&last_order)), some(clob_v2::order_id(&last_order)))
-    } else \{
-        (orders, false, none(), none())
-    };
-
-    OrderPage \{
-        orders,
-        has_next_page,
-        next_tick_level,
-        next_order_id
-    }
-}
-
- - - -
- - - -## Function `iter_asks` - - - -

-public fun iter_asks<T1, T2>(pool: &clob_v2::Pool<T1, T2>, start_tick_level: option::Option<u64>, start_order_id: option::Option<u64>, min_expire_timestamp: option::Option<u64>, max_id: option::Option<u64>, ascending: bool): order_query::OrderPage
-
- - - -
-Implementation - - -

-public fun iter_asks<T1, T2>(
-    pool: &Pool<T1, T2>,
-    // tick level to start from
-    start_tick_level: Option<u64>,
-    // order id within that tick level to start from
-    start_order_id: Option<u64>,
-    // if provided, do not include orders with an expire timestamp less than the provided value (expired order),
-    // value is in microseconds
-    min_expire_timestamp: Option<u64>,
-    // do not show orders with an ID larger than max_id--
-    // i.e., orders added later than this one
-    max_id: Option<u64>,
-    // if true, the orders are returned in ascending tick level.
-    ascending: bool,
-): OrderPage \{
-    let asks = clob_v2::asks(pool);
-    let mut orders = iter_ticks_internal(
-        asks,
-        start_tick_level,
-        start_order_id,
-        min_expire_timestamp,
-        max_id,
-        ascending
-    );
-    let (orders, has_next_page, next_tick_level, next_order_id) = if (vector::length(&orders) > PAGE_LIMIT) \{
-        let last_order = vector::pop_back(&mut orders);
-        (orders, true, some(clob_v2::tick_level(&last_order)), some(clob_v2::order_id(&last_order)))
-    } else \{
-        (orders, false, none(), none())
-    };
-
-    OrderPage \{
-        orders,
-        has_next_page,
-        next_tick_level,
-        next_order_id
-    }
-}
-
- - - -
- - - -## Function `iter_ticks_internal` - - - -

-fun iter_ticks_internal(ticks: &critbit::CritbitTree<clob_v2::TickLevel>, start_tick_level: option::Option<u64>, start_order_id: option::Option<u64>, min_expire_timestamp: option::Option<u64>, max_id: option::Option<u64>, ascending: bool): vector<clob_v2::Order>
-
- - - -
-Implementation - - -

-fun iter_ticks_internal(
-    ticks: &CritbitTree<TickLevel>,
-    // tick level to start from
-    start_tick_level: Option<u64>,
-    // order id within that tick level to start from
-    mut start_order_id: Option<u64>,
-    // if provided, do not include orders with an expire timestamp less than the provided value (expired order),
-    // value is in microseconds
-    min_expire_timestamp: Option<u64>,
-    // do not show orders with an ID larger than max_id--
-    // i.e., orders added later than this one
-    max_id: Option<u64>,
-    // if true, the orders are returned in ascending tick level.
-    ascending: bool,
-): vector<Order> \{
-    let mut tick_level_key = if (option::is_some(&start_tick_level)) \{
-        option::destroy_some(start_tick_level)
-    } else \{
-        let (key, _) = if (ascending) \{
-            critbit::min_leaf(ticks)
-        }else \{
-            critbit::max_leaf(ticks)
-        };
-        key
-    };
-
-    let mut orders = vector[];
-
-    while (tick_level_key != 0 && vector::length(&orders) < PAGE_LIMIT + 1) \{
-        let tick_level = critbit::borrow_leaf_by_key(ticks, tick_level_key);
-        let open_orders = clob_v2::open_orders(tick_level);
-
-        let mut next_order_key = if (option::is_some(&start_order_id)) \{
-            let key = option::destroy_some(start_order_id);
-            if (!linked_table::contains(open_orders, key)) \{
-                let (next_leaf, _) = if (ascending) \{
-                    critbit::next_leaf(ticks, tick_level_key)
-                }else \{
-                    critbit::previous_leaf(ticks, tick_level_key)
-                };
-                tick_level_key = next_leaf;
-                continue
-            };
-            start_order_id = option::none();
-            some(key)
-        }else \{
-            *linked_table::front(open_orders)
-        };
-
-        while (option::is_some(&next_order_key) && vector::length(&orders) < PAGE_LIMIT + 1) \{
-            let key = option::destroy_some(next_order_key);
-            let order = linked_table::borrow(open_orders, key);
-
-            // if the order id is greater than max_id, we end the iteration for this tick level.
-            if (option::is_some(&max_id) && key > option::destroy_some(max_id)) \{
-                break
-            };
-
-            next_order_key = *linked_table::next(open_orders, key);
-
-            // if expire timestamp is set, and if the order is expired, we skip it.
-            if (option::is_none(&min_expire_timestamp) ||
-                clob_v2::expire_timestamp(order) > option::destroy_some(min_expire_timestamp)) \{
-                vector::push_back(&mut orders, clob_v2::clone_order(order));
-            };
-        };
-        let (next_leaf, _) = if (ascending) \{
-            critbit::next_leaf(ticks, tick_level_key)
-        }else \{
-            critbit::previous_leaf(ticks, tick_level_key)
-        };
-        tick_level_key = next_leaf;
-    };
-    orders
-}
-
- - - -
- - - -## Function `orders` - - - -

-public fun orders(page: &order_query::OrderPage): &vector<clob_v2::Order>
-
- - - -
-Implementation - - -

-public fun orders(page: &OrderPage): &vector<Order> \{
-    &page.orders
-}
-
- - - -
- - - -## Function `has_next_page` - - - -

-public fun has_next_page(page: &order_query::OrderPage): bool
-
- - - -
-Implementation - - -

-public fun has_next_page(page: &OrderPage): bool \{
-    page.has_next_page
-}
-
- - - -
- - - -## Function `next_tick_level` - - - -

-public fun next_tick_level(page: &order_query::OrderPage): option::Option<u64>
-
- - - -
-Implementation - - -

-public fun next_tick_level(page: &OrderPage): Option<u64> \{
-    page.next_tick_level
-}
-
- - - -
- - - -## Function `next_order_id` - - - -

-public fun next_order_id(page: &order_query::OrderPage): option::Option<u64>
-
- - - -
-Implementation - - -

-public fun next_order_id(page: &OrderPage): Option<u64> \{
-    page.next_order_id
-}
-
- - - -
- - - -## Function `order_id` - - - -

-public fun order_id(order: &clob_v2::Order): u64
-
- - - -
-Implementation - - -

-public fun order_id(order: &Order): u64 \{
-    clob_v2::order_id(order)
-}
-
- - - -
- - - -## Function `tick_level` - - - -

-public fun tick_level(order: &clob_v2::Order): u64
-
- - - -
-Implementation - - -

-public fun tick_level(order: &Order): u64 \{
-    clob_v2::tick_level(order)
-}
-
- - - -
diff --git a/crates/iota-framework/docs/iota-framework/address.mdx b/crates/iota-framework/docs/iota-framework/address.mdx deleted file mode 100644 index 9f548dc68a9..00000000000 --- a/crates/iota-framework/docs/iota-framework/address.mdx +++ /dev/null @@ -1,365 +0,0 @@ ---- -title: Module `0x2::address` ---- -import Link from '@docusaurus/Link'; - - - - -- [Constants](#@Constants_0) -- [Function `to_u256`](#0x2_address_to_u256) -- [Function `from_u256`](#0x2_address_from_u256) -- [Function `from_bytes`](#0x2_address_from_bytes) -- [Function `to_bytes`](#0x2_address_to_bytes) -- [Function `to_ascii_string`](#0x2_address_to_ascii_string) -- [Function `to_string`](#0x2_address_to_string) -- [Function `from_ascii_bytes`](#0x2_address_from_ascii_bytes) -- [Function `hex_char_value`](#0x2_address_hex_char_value) -- [Function `length`](#0x2_address_length) -- [Function `max`](#0x2_address_max) - - -

-use 0x1::ascii;
-use 0x1::bcs;
-use 0x1::string;
-use 0x2::hex;
-
- - - - - -## Constants - - - - -Error from -from_bytes when it is supplied too many or too few bytes. - - -

-const EAddressParseError: u64 = 0;
-
- - - - - -The length of an address, in bytes - - -

-const LENGTH: u64 = 32;
-
- - - - - - - -

-const MAX: u256 = 115792089237316195423570985008687907853269984665640564039457584007913129639935;
-
- - - - - -## Function `to_u256` - -Convert -a into a u256 by interpreting -a as the bytes of a big-endian integer -(e.g., -to_u256(0x1) == 1) - - -

-public fun to_u256(a: address): u256
-
- - - -
-Implementation - - -

-public native fun to_u256(a: address): u256;
-
- - - -
- - - -## Function `from_u256` - -Convert -n into an address by encoding it as a big-endian integer (e.g., -from_u256(1) = @0x1) -Aborts if -n > -MAX_ADDRESS - - -

-public fun from_u256(n: u256): address
-
- - - -
-Implementation - - -

-public native fun from_u256(n: u256): address;
-
- - - -
- - - -## Function `from_bytes` - -Convert -bytes into an address. -Aborts with -EAddressParseError if the length of -bytes is not 32 - - -

-public fun from_bytes(bytes: vector<u8>): address
-
- - - -
-Implementation - - -

-public native fun from_bytes(bytes: vector<u8>): address;
-
- - - -
- - - -## Function `to_bytes` - -Convert -a into BCS-encoded bytes. - - -

-public fun to_bytes(a: address): vector<u8>
-
- - - -
-Implementation - - -

-public fun to_bytes(a: address): vector<u8> \{
-    bcs::to_bytes(&a)
-}
-
- - - -
- - - -## Function `to_ascii_string` - -Convert -a to a hex-encoded ASCII string - - -

-public fun to_ascii_string(a: address): ascii::String
-
- - - -
-Implementation - - -

-public fun to_ascii_string(a: address): ascii::String \{
-    hex::encode(to_bytes(a)).to_ascii_string()
-}
-
- - - -
- - - -## Function `to_string` - -Convert -a to a hex-encoded string - - -

-public fun to_string(a: address): string::String
-
- - - -
-Implementation - - -

-public fun to_string(a: address): string::String \{
-    to_ascii_string(a).to_string()
-}
-
- - - -
- - - -## Function `from_ascii_bytes` - -Converts an ASCII string to an address, taking the numerical value for each character. The -string must be Base16 encoded, and thus exactly 64 characters long. -For example, the string "00000000000000000000000000000000000000000000000000000000DEADB33F" -will be converted to the address @0xDEADB33F. -Aborts with -EAddressParseError if the length of -s is not 64, -or if an invalid character is encountered. - - -

-public fun from_ascii_bytes(bytes: &vector<u8>): address
-
- - - -
-Implementation - - -

-public fun from_ascii_bytes(bytes: &vector<u8>): address \{
-    assert!(bytes.length() == 64, EAddressParseError);
-    let mut hex_bytes = vector[];
-    let mut i = 0;
-    while (i < 64) \{
-        let hi = hex_char_value(bytes[i]);
-        let lo = hex_char_value(bytes[i+1]);
-        hex_bytes.push_back((hi << 4) | lo);
-        i = i + 2;
-    };
-    from_bytes(hex_bytes)
-}
-
- - - -
- - - -## Function `hex_char_value` - - - -

-fun hex_char_value(c: u8): u8
-
- - - -
-Implementation - - -

-fun hex_char_value(c: u8): u8 \{
-    if (c >= 48 && c <= 57) c - 48 // 0-9
-    else if (c >= 65 && c <= 70) c - 55 // A-F
-    else if (c >= 97 && c <= 102) c - 87 // a-f
-    else abort EAddressParseError
-}
-
- - - -
- - - -## Function `length` - -Length of a Iota address in bytes - - -

-public fun length(): u64
-
- - - -
-Implementation - - -

-public fun length(): u64 \{
-    LENGTH
-}
-
- - - -
- - - -## Function `max` - -Largest possible address - - -

-public fun max(): u256
-
- - - -
-Implementation - - -

-public fun max(): u256 \{
-    MAX
-}
-
- - - -
diff --git a/crates/iota-framework/docs/iota-framework/authenticator_state.mdx b/crates/iota-framework/docs/iota-framework/authenticator_state.mdx deleted file mode 100644 index ff0f75a375c..00000000000 --- a/crates/iota-framework/docs/iota-framework/authenticator_state.mdx +++ /dev/null @@ -1,858 +0,0 @@ ---- -title: Module `0x2::authenticator_state` ---- -import Link from '@docusaurus/Link'; - - - - -- [Resource `AuthenticatorState`](#0x2_authenticator_state_AuthenticatorState) -- [Struct `AuthenticatorStateInner`](#0x2_authenticator_state_AuthenticatorStateInner) -- [Struct `JWK`](#0x2_authenticator_state_JWK) -- [Struct `JwkId`](#0x2_authenticator_state_JwkId) -- [Struct `ActiveJwk`](#0x2_authenticator_state_ActiveJwk) -- [Constants](#@Constants_0) -- [Function `active_jwk_equal`](#0x2_authenticator_state_active_jwk_equal) -- [Function `jwk_equal`](#0x2_authenticator_state_jwk_equal) -- [Function `jwk_id_equal`](#0x2_authenticator_state_jwk_id_equal) -- [Function `string_bytes_lt`](#0x2_authenticator_state_string_bytes_lt) -- [Function `jwk_lt`](#0x2_authenticator_state_jwk_lt) -- [Function `create`](#0x2_authenticator_state_create) -- [Function `load_inner_mut`](#0x2_authenticator_state_load_inner_mut) -- [Function `load_inner`](#0x2_authenticator_state_load_inner) -- [Function `check_sorted`](#0x2_authenticator_state_check_sorted) -- [Function `update_authenticator_state`](#0x2_authenticator_state_update_authenticator_state) -- [Function `deduplicate`](#0x2_authenticator_state_deduplicate) -- [Function `expire_jwks`](#0x2_authenticator_state_expire_jwks) -- [Function `get_active_jwks`](#0x2_authenticator_state_get_active_jwks) - - -

-use 0x1::option;
-use 0x1::string;
-use 0x2::dynamic_field;
-use 0x2::math;
-use 0x2::object;
-use 0x2::transfer;
-use 0x2::tx_context;
-
- - - - - -## Resource `AuthenticatorState` - -Singleton shared object which stores the global authenticator state. -The actual state is stored in a dynamic field of type AuthenticatorStateInner to support -future versions of the authenticator state. - - -

-struct AuthenticatorState has key
-
- - - -
-Fields - - -
-
- -id: object::UID -
-
- -
-
- -version: u64 -
-
- -
-
- - -
- - - -## Struct `AuthenticatorStateInner` - - - -

-struct AuthenticatorStateInner has store
-
- - - -
-Fields - - -
-
- -version: u64 -
-
- -
-
- -active_jwks: vector<authenticator_state::ActiveJwk> -
-
- List of currently active JWKs. -
-
- - -
- - - -## Struct `JWK` - -Must match the JWK struct in fastcrypto-zkp - - -

-struct JWK has copy, drop, store
-
- - - -
-Fields - - -
-
- -kty: string::String -
-
- -
-
- -e: string::String -
-
- -
-
- -n: string::String -
-
- -
-
- -alg: string::String -
-
- -
-
- - -
- - - -## Struct `JwkId` - -Must match the JwkId struct in fastcrypto-zkp - - -

-struct JwkId has copy, drop, store
-
- - - -
-Fields - - -
-
- -iss: string::String -
-
- -
-
- -kid: string::String -
-
- -
-
- - -
- - - -## Struct `ActiveJwk` - - - -

-struct ActiveJwk has copy, drop, store
-
- - - -
-Fields - - -
-
- -jwk_id: authenticator_state::JwkId -
-
- -
-
- -jwk: authenticator_state::JWK -
-
- -
-
- -epoch: u64 -
-
- -
-
- - -
- - - -## Constants - - - - -Sender is not @0x0 the system address. - - -

-const ENotSystemAddress: u64 = 0;
-
- - - - - - - -

-const CurrentVersion: u64 = 1;
-
- - - - - - - -

-const EJwksNotSorted: u64 = 2;
-
- - - - - - - -

-const EWrongInnerVersion: u64 = 1;
-
- - - - - -## Function `active_jwk_equal` - - - -

-fun active_jwk_equal(a: &authenticator_state::ActiveJwk, b: &authenticator_state::ActiveJwk): bool
-
- - - -
-Implementation - - -

-fun active_jwk_equal(a: &ActiveJwk, b: &ActiveJwk): bool \{
-    // note: epoch is ignored
-    jwk_equal(&a.jwk, &b.jwk) && jwk_id_equal(&a.jwk_id, &b.jwk_id)
-}
-
- - - -
- - - -## Function `jwk_equal` - - - -

-fun jwk_equal(a: &authenticator_state::JWK, b: &authenticator_state::JWK): bool
-
- - - -
-Implementation - - -

-fun jwk_equal(a: &JWK, b: &JWK): bool \{
-    (&a.kty == &b.kty) &&
-       (&a.e == &b.e) &&
-       (&a.n == &b.n) &&
-       (&a.alg == &b.alg)
-}
-
- - - -
- - - -## Function `jwk_id_equal` - - - -

-fun jwk_id_equal(a: &authenticator_state::JwkId, b: &authenticator_state::JwkId): bool
-
- - - -
-Implementation - - -

-fun jwk_id_equal(a: &JwkId, b: &JwkId): bool \{
-    (&a.iss == &b.iss) && (&a.kid == &b.kid)
-}
-
- - - -
- - - -## Function `string_bytes_lt` - - - -

-fun string_bytes_lt(a: &string::String, b: &string::String): bool
-
- - - -
-Implementation - - -

-fun string_bytes_lt(a: &String, b: &String): bool \{
-    let a_bytes = a.bytes();
-    let b_bytes = b.bytes();
-
-    if (a_bytes.length() < b_bytes.length()) \{
-        true
-    } else if (a_bytes.length() > b_bytes.length()) \{
-        false
-    } else \{
-        let mut i = 0;
-        while (i < a_bytes.length()) \{
-            let a_byte = a_bytes[i];
-            let b_byte = b_bytes[i];
-            if (a_byte < b_byte) \{
-                return true
-            } else if (a_byte > b_byte) \{
-                return false
-            };
-            i = i + 1;
-        };
-        // all bytes are equal
-        false
-    }
-}
-
- - - -
- - - -## Function `jwk_lt` - - - -

-fun jwk_lt(a: &authenticator_state::ActiveJwk, b: &authenticator_state::ActiveJwk): bool
-
- - - -
-Implementation - - -

-fun jwk_lt(a: &ActiveJwk, b: &ActiveJwk): bool \{
-    // note: epoch is ignored
-    if (&a.jwk_id.iss != &b.jwk_id.iss) \{
-        return string_bytes_lt(&a.jwk_id.iss, &b.jwk_id.iss)
-    };
-    if (&a.jwk_id.kid != &b.jwk_id.kid) \{
-        return string_bytes_lt(&a.jwk_id.kid, &b.jwk_id.kid)
-    };
-    if (&a.jwk.kty != &b.jwk.kty) \{
-        return string_bytes_lt(&a.jwk.kty, &b.jwk.kty)
-    };
-    if (&a.jwk.e != &b.jwk.e) \{
-        return string_bytes_lt(&a.jwk.e, &b.jwk.e)
-    };
-    if (&a.jwk.n != &b.jwk.n) \{
-        return string_bytes_lt(&a.jwk.n, &b.jwk.n)
-    };
-    string_bytes_lt(&a.jwk.alg, &b.jwk.alg)
-}
-
- - - -
- - - -## Function `create` - -Create and share the AuthenticatorState object. This function is call exactly once, when -the authenticator state object is first created. -Can only be called by genesis or change_epoch transactions. - - -

-fun create(ctx: &tx_context::TxContext)
-
- - - -
-Implementation - - -

-fun create(ctx: &TxContext) \{
-    assert!(ctx.sender() == @0x0, ENotSystemAddress);
-
-    let version = CurrentVersion;
-
-    let inner = AuthenticatorStateInner \{
-        version,
-        active_jwks: vector[],
-    };
-
-    let mut self = AuthenticatorState \{
-        id: object::authenticator_state(),
-        version,
-    };
-
-    dynamic_field::add(&mut self.id, version, inner);
-    transfer::share_object(self);
-}
-
- - - -
- - - -## Function `load_inner_mut` - - - -

-fun load_inner_mut(self: &mut authenticator_state::AuthenticatorState): &mut authenticator_state::AuthenticatorStateInner
-
- - - -
-Implementation - - -

-fun load_inner_mut(
-    self: &mut AuthenticatorState,
-): &mut AuthenticatorStateInner \{
-    let version = self.version;
-
-    // replace this with a lazy update function when we add a new version of the inner object.
-    assert!(version == CurrentVersion, EWrongInnerVersion);
-
-    let inner: &mut AuthenticatorStateInner = dynamic_field::borrow_mut(&mut self.id, self.version);
-
-    assert!(inner.version == version, EWrongInnerVersion);
-    inner
-}
-
- - - -
- - - -## Function `load_inner` - - - -

-fun load_inner(self: &authenticator_state::AuthenticatorState): &authenticator_state::AuthenticatorStateInner
-
- - - -
-Implementation - - -

-fun load_inner(
-    self: &AuthenticatorState,
-): &AuthenticatorStateInner \{
-    let version = self.version;
-
-    // replace this with a lazy update function when we add a new version of the inner object.
-    assert!(version == CurrentVersion, EWrongInnerVersion);
-
-    let inner: &AuthenticatorStateInner = dynamic_field::borrow(&self.id, self.version);
-
-    assert!(inner.version == version, EWrongInnerVersion);
-    inner
-}
-
- - - -
- - - -## Function `check_sorted` - - - -

-fun check_sorted(new_active_jwks: &vector<authenticator_state::ActiveJwk>)
-
- - - -
-Implementation - - -

-fun check_sorted(new_active_jwks: &vector<ActiveJwk>) \{
-    let mut i = 0;
-    while (i < new_active_jwks.length() - 1) \{
-        let a = &new_active_jwks[i];
-        let b = &new_active_jwks[i + 1];
-        assert!(jwk_lt(a, b), EJwksNotSorted);
-        i = i + 1;
-    };
-}
-
- - - -
- - - -## Function `update_authenticator_state` - -Record a new set of active_jwks. Called when executing the AuthenticatorStateUpdate system -transaction. The new input vector must be sorted and must not contain duplicates. -If a new JWK is already present, but with a previous epoch, then the epoch is updated to -indicate that the JWK has been validated in the current epoch and should not be expired. - - -

-fun update_authenticator_state(self: &mut authenticator_state::AuthenticatorState, new_active_jwks: vector<authenticator_state::ActiveJwk>, ctx: &tx_context::TxContext)
-
- - - -
-Implementation - - -

-fun update_authenticator_state(
-    self: &mut AuthenticatorState,
-    new_active_jwks: vector<ActiveJwk>,
-    ctx: &TxContext,
-) \{
-    // Validator will make a special system call with sender set as 0x0.
-    assert!(ctx.sender() == @0x0, ENotSystemAddress);
-
-    check_sorted(&new_active_jwks);
-    let new_active_jwks = deduplicate(new_active_jwks);
-
-    let inner = self.load_inner_mut();
-
-    let mut res = vector[];
-    let mut i = 0;
-    let mut j = 0;
-    let active_jwks_len = inner.active_jwks.length();
-    let new_active_jwks_len = new_active_jwks.length();
-
-    while (i < active_jwks_len && j < new_active_jwks_len) \{
-        let old_jwk = &inner.active_jwks[i];
-        let new_jwk = &new_active_jwks[j];
-
-        // when they are equal, push only one, but use the max epoch of the two
-        if (active_jwk_equal(old_jwk, new_jwk)) \{
-            let mut jwk = *old_jwk;
-            jwk.epoch = math::max(old_jwk.epoch, new_jwk.epoch);
-            res.push_back(jwk);
-            i = i + 1;
-            j = j + 1;
-        } else if (jwk_id_equal(&old_jwk.jwk_id, &new_jwk.jwk_id)) \{
-            // if only jwk_id is equal, then the key has changed. Providers should not send
-            // JWKs like this, but if they do, we must ignore the new JWK to avoid having a
-            // liveness / forking issues
-            res.push_back(*old_jwk);
-            i = i + 1;
-            j = j + 1;
-        } else if (jwk_lt(old_jwk, new_jwk)) \{
-            res.push_back(*old_jwk);
-            i = i + 1;
-        } else \{
-            res.push_back(*new_jwk);
-            j = j + 1;
-        }
-    };
-
-    while (i < active_jwks_len) \{
-        res.push_back(inner.active_jwks[i]);
-        i = i + 1;
-    };
-    while (j < new_active_jwks_len) \{
-        res.push_back(new_active_jwks[j]);
-        j = j + 1;
-    };
-
-    inner.active_jwks = res;
-}
-
- - - -
- - - -## Function `deduplicate` - - - -

-fun deduplicate(jwks: vector<authenticator_state::ActiveJwk>): vector<authenticator_state::ActiveJwk>
-
- - - -
-Implementation - - -

-fun deduplicate(jwks: vector<ActiveJwk>): vector<ActiveJwk> \{
-    let mut res = vector[];
-    let mut i = 0;
-    let mut prev: Option<JwkId> = option::none();
-    while (i < jwks.length()) \{
-        let jwk = &jwks[i];
-        if (prev.is_none()) \{
-            prev.fill(jwk.jwk_id);
-        } else if (jwk_id_equal(prev.borrow(), &jwk.jwk_id)) \{
-            // skip duplicate jwks in input
-            i = i + 1;
-            continue
-        } else \{
-            *prev.borrow_mut() = jwk.jwk_id;
-        };
-        res.push_back(*jwk);
-        i = i + 1;
-    };
-    res
-}
-
- - - -
- - - -## Function `expire_jwks` - - - -

-fun expire_jwks(self: &mut authenticator_state::AuthenticatorState, min_epoch: u64, ctx: &tx_context::TxContext)
-
- - - -
-Implementation - - -

-fun expire_jwks(
-    self: &mut AuthenticatorState,
-    // any jwk below this epoch is not retained
-    min_epoch: u64,
-    ctx: &TxContext) \{
-    // This will only be called by iota_system::advance_epoch
-    assert!(ctx.sender() == @0x0, ENotSystemAddress);
-
-    let inner = load_inner_mut(self);
-
-    let len = inner.active_jwks.length();
-
-    // first we count how many jwks from each issuer are above the min_epoch
-    // and store the counts in a vector that parallels the (sorted) active_jwks vector
-    let mut issuer_max_epochs = vector[];
-    let mut i = 0;
-    let mut prev_issuer: Option<String> = option::none();
-
-    while (i < len) \{
-        let cur = &inner.active_jwks[i];
-        let cur_iss = &cur.jwk_id.iss;
-        if (prev_issuer.is_none()) \{
-            prev_issuer.fill(*cur_iss);
-            issuer_max_epochs.push_back(cur.epoch);
-        } else \{
-            if (cur_iss == prev_issuer.borrow()) \{
-                let back = issuer_max_epochs.length() - 1;
-                let prev_max_epoch = &mut issuer_max_epochs[back];
-                *prev_max_epoch = math::max(*prev_max_epoch, cur.epoch);
-            } else \{
-                *prev_issuer.borrow_mut() = *cur_iss;
-                issuer_max_epochs.push_back(cur.epoch);
-            }
-        };
-        i = i + 1;
-    };
-
-    // Now, filter out any JWKs that are below the min_epoch, unless that issuer has no
-    // JWKs >= the min_epoch, in which case we keep all of them.
-    let mut new_active_jwks: vector<ActiveJwk> = vector[];
-    let mut prev_issuer: Option<String> = option::none();
-    let mut i = 0;
-    let mut j = 0;
-    while (i < len) \{
-        let jwk = &inner.active_jwks[i];
-        let cur_iss = &jwk.jwk_id.iss;
-
-        if (prev_issuer.is_none()) \{
-            prev_issuer.fill(*cur_iss);
-        } else if (cur_iss != prev_issuer.borrow()) \{
-            *prev_issuer.borrow_mut() = *cur_iss;
-            j = j + 1;
-        };
-
-        let max_epoch_for_iss = &issuer_max_epochs[j];
-
-        // TODO: if the iss for this jwk has *no* jwks that meet the minimum epoch,
-        // then expire nothing.
-        if (*max_epoch_for_iss < min_epoch || jwk.epoch >= min_epoch) \{
-            new_active_jwks.push_back(*jwk);
-        };
-        i = i + 1;
-    };
-    inner.active_jwks = new_active_jwks;
-}
-
- - - -
- - - -## Function `get_active_jwks` - -Get the current active_jwks. Called when the node starts up in order to load the current -JWK state from the chain. - - -

-fun get_active_jwks(self: &authenticator_state::AuthenticatorState, ctx: &tx_context::TxContext): vector<authenticator_state::ActiveJwk>
-
- - - -
-Implementation - - -

-fun get_active_jwks(
-    self: &AuthenticatorState,
-    ctx: &TxContext,
-): vector<ActiveJwk> \{
-    assert!(ctx.sender() == @0x0, ENotSystemAddress);
-    self.load_inner().active_jwks
-}
-
- - - -
diff --git a/crates/iota-framework/docs/iota-framework/bag.mdx b/crates/iota-framework/docs/iota-framework/bag.mdx deleted file mode 100644 index a88c6befe9a..00000000000 --- a/crates/iota-framework/docs/iota-framework/bag.mdx +++ /dev/null @@ -1,426 +0,0 @@ ---- -title: Module `0x2::bag` ---- -import Link from '@docusaurus/Link'; - - -A bag is a heterogeneous map-like collection. The collection is similar to -iota::table in that -its keys and values are not stored within the -Bag value, but instead are stored using Iota's -object system. The -Bag struct acts only as a handle into the object system to retrieve those -keys and values. -Note that this means that -Bag values with exactly the same key-value mapping will not be -equal, with -==, at runtime. For example -``` -let bag1 = bag::new(); -let bag2 = bag::new(); -bag::add(&mut bag1, 0, false); -bag::add(&mut bag1, 1, true); -bag::add(&mut bag2, 0, false); -bag::add(&mut bag2, 1, true); -// bag1 does not equal bag2, despite having the same entries -assert!(&bag1 != &bag2, 0); -``` -At it's core, -iota::bag is a wrapper around -UID that allows for access to - -iota::dynamic_field while preventing accidentally stranding field values. A -UID can be -deleted, even if it has dynamic fields associated with it, but a bag, on the other hand, must be -empty to be destroyed. - - -- [Resource `Bag`](#0x2_bag_Bag) -- [Constants](#@Constants_0) -- [Function `new`](#0x2_bag_new) -- [Function `add`](#0x2_bag_add) -- [Function `borrow`](#0x2_bag_borrow) -- [Function `borrow_mut`](#0x2_bag_borrow_mut) -- [Function `remove`](#0x2_bag_remove) -- [Function `contains`](#0x2_bag_contains) -- [Function `contains_with_type`](#0x2_bag_contains_with_type) -- [Function `length`](#0x2_bag_length) -- [Function `is_empty`](#0x2_bag_is_empty) -- [Function `destroy_empty`](#0x2_bag_destroy_empty) - - -

-use 0x2::dynamic_field;
-use 0x2::object;
-use 0x2::tx_context;
-
- - - - - -## Resource `Bag` - - - -

-struct Bag has store, key
-
- - - -
-Fields - - -
-
- -id: object::UID -
-
- the ID of this bag -
-
- -size: u64 -
-
- the number of key-value pairs in the bag -
-
- - -
- - - -## Constants - - - - - - -

-const EBagNotEmpty: u64 = 0;
-
- - - - - -## Function `new` - -Creates a new, empty bag - - -

-public fun new(ctx: &mut tx_context::TxContext): bag::Bag
-
- - - -
-Implementation - - -

-public fun new(ctx: &mut TxContext): Bag \{
-    Bag \{
-        id: object::new(ctx),
-        size: 0,
-    }
-}
-
- - - -
- - - -## Function `add` - -Adds a key-value pair to the bag -bag: &mut Bag -Aborts with -iota::dynamic_field::EFieldAlreadyExists if the bag already has an entry with -that key -k: K. - - -

-public fun add<K: copy, drop, store, V: store>(bag: &mut bag::Bag, k: K, v: V)
-
- - - -
-Implementation - - -

-public fun add<K: copy + drop + store, V: store>(bag: &mut Bag, k: K, v: V) \{
-    field::add(&mut bag.id, k, v);
-    bag.size = bag.size + 1;
-}
-
- - - -
- - - -## Function `borrow` - -Immutable borrows the value associated with the key in the bag -bag: &Bag. -Aborts with -iota::dynamic_field::EFieldDoesNotExist if the bag does not have an entry with -that key -k: K. -Aborts with -iota::dynamic_field::EFieldTypeMismatch if the bag has an entry for the key, but -the value does not have the specified type. - - -

-public fun borrow<K: copy, drop, store, V: store>(bag: &bag::Bag, k: K): &V
-
- - - -
-Implementation - - -

-public fun borrow<K: copy + drop + store, V: store>(bag: &Bag, k: K): &V \{
-    field::borrow(&bag.id, k)
-}
-
- - - -
- - - -## Function `borrow_mut` - -Mutably borrows the value associated with the key in the bag -bag: &mut Bag. -Aborts with -iota::dynamic_field::EFieldDoesNotExist if the bag does not have an entry with -that key -k: K. -Aborts with -iota::dynamic_field::EFieldTypeMismatch if the bag has an entry for the key, but -the value does not have the specified type. - - -

-public fun borrow_mut<K: copy, drop, store, V: store>(bag: &mut bag::Bag, k: K): &mut V
-
- - - -
-Implementation - - -

-public fun borrow_mut<K: copy + drop + store, V: store>(bag: &mut Bag, k: K): &mut V \{
-    field::borrow_mut(&mut bag.id, k)
-}
-
- - - -
- - - -## Function `remove` - -Mutably borrows the key-value pair in the bag -bag: &mut Bag and returns the value. -Aborts with -iota::dynamic_field::EFieldDoesNotExist if the bag does not have an entry with -that key -k: K. -Aborts with -iota::dynamic_field::EFieldTypeMismatch if the bag has an entry for the key, but -the value does not have the specified type. - - -

-public fun remove<K: copy, drop, store, V: store>(bag: &mut bag::Bag, k: K): V
-
- - - -
-Implementation - - -

-public fun remove<K: copy + drop + store, V: store>(bag: &mut Bag, k: K): V \{
-    let v = field::remove(&mut bag.id, k);
-    bag.size = bag.size - 1;
-    v
-}
-
- - - -
- - - -## Function `contains` - -Returns true iff there is an value associated with the key -k: K in the bag -bag: &Bag - - -

-public fun contains<K: copy, drop, store>(bag: &bag::Bag, k: K): bool
-
- - - -
-Implementation - - -

-public fun contains<K: copy + drop + store>(bag: &Bag, k: K): bool \{
-    field::exists_<K>(&bag.id, k)
-}
-
- - - -
- - - -## Function `contains_with_type` - -Returns true iff there is an value associated with the key -k: K in the bag -bag: &Bag -with an assigned value of type -V - - -

-public fun contains_with_type<K: copy, drop, store, V: store>(bag: &bag::Bag, k: K): bool
-
- - - -
-Implementation - - -

-public fun contains_with_type<K: copy + drop + store, V: store>(bag: &Bag, k: K): bool \{
-    field::exists_with_type<K, V>(&bag.id, k)
-}
-
- - - -
- - - -## Function `length` - -Returns the size of the bag, the number of key-value pairs - - -

-public fun length(bag: &bag::Bag): u64
-
- - - -
-Implementation - - -

-public fun length(bag: &Bag): u64 \{
-    bag.size
-}
-
- - - -
- - - -## Function `is_empty` - -Returns true iff the bag is empty (if -length returns -0) - - -

-public fun is_empty(bag: &bag::Bag): bool
-
- - - -
-Implementation - - -

-public fun is_empty(bag: &Bag): bool \{
-    bag.size == 0
-}
-
- - - -
- - - -## Function `destroy_empty` - -Destroys an empty bag -Aborts with -EBagNotEmpty if the bag still contains values - - -

-public fun destroy_empty(bag: bag::Bag)
-
- - - -
-Implementation - - -

-public fun destroy_empty(bag: Bag) \{
-    let Bag \{ id, size } = bag;
-    assert!(size == 0, EBagNotEmpty);
-    id.delete()
-}
-
- - - -
diff --git a/crates/iota-framework/docs/iota-framework/balance.mdx b/crates/iota-framework/docs/iota-framework/balance.mdx deleted file mode 100644 index ba5de1a5922..00000000000 --- a/crates/iota-framework/docs/iota-framework/balance.mdx +++ /dev/null @@ -1,575 +0,0 @@ ---- -title: Module `0x2::balance` ---- -import Link from '@docusaurus/Link'; - - -A storable handler for Balances in general. Is used in the -Coin -module to allow balance operations and can be used to implement -custom coins with -Supply and -Balances. - - -- [Struct `Supply`](#0x2_balance_Supply) -- [Struct `Balance`](#0x2_balance_Balance) -- [Constants](#@Constants_0) -- [Function `value`](#0x2_balance_value) -- [Function `supply_value`](#0x2_balance_supply_value) -- [Function `create_supply`](#0x2_balance_create_supply) -- [Function `increase_supply`](#0x2_balance_increase_supply) -- [Function `decrease_supply`](#0x2_balance_decrease_supply) -- [Function `zero`](#0x2_balance_zero) -- [Function `join`](#0x2_balance_join) -- [Function `split`](#0x2_balance_split) -- [Function `withdraw_all`](#0x2_balance_withdraw_all) -- [Function `destroy_zero`](#0x2_balance_destroy_zero) -- [Function `create_staking_rewards`](#0x2_balance_create_staking_rewards) -- [Function `destroy_storage_rebates`](#0x2_balance_destroy_storage_rebates) -- [Function `destroy_genesis_supply`](#0x2_balance_destroy_genesis_supply) -- [Function `destroy_supply`](#0x2_balance_destroy_supply) - - -

-use 0x2::tx_context;
-
- - - - - -## Struct `Supply` - -A Supply of T. Used for minting and burning. -Wrapped into a -TreasuryCap in the -Coin module. - - -

-struct Supply<T> has store
-
- - - -
-Fields - - -
-
- -value: u64 -
-
- -
-
- - -
- - - -## Struct `Balance` - -Storable balance - an inner struct of a Coin type. -Can be used to store coins which don't need the key ability. - - -

-struct Balance<T> has store
-
- - - -
-Fields - - -
-
- -value: u64 -
-
- -
-
- - -
- - - -## Constants - - - - -Sender is not @0x0 the system address. - - -

-const ENotSystemAddress: u64 = 3;
-
- - - - - -For when trying to destroy a non-zero balance. - - -

-const ENonZero: u64 = 0;
-
- - - - - -For when trying to withdraw more than there is. - - -

-const ENotEnough: u64 = 2;
-
- - - - - -Epoch is not 0 (the genesis epoch). - - -

-const ENotGenesisEpoch: u64 = 4;
-
- - - - - -For when an overflow is happening on Supply operations. - - -

-const EOverflow: u64 = 1;
-
- - - - - -## Function `value` - -Get the amount stored in a -Balance. - - -

-public fun value<T>(self: &balance::Balance<T>): u64
-
- - - -
-Implementation - - -

-public fun value<T>(self: &Balance<T>): u64 \{
-    self.value
-}
-
- - - -
- - - -## Function `supply_value` - -Get the -Supply value. - - -

-public fun supply_value<T>(supply: &balance::Supply<T>): u64
-
- - - -
-Implementation - - -

-public fun supply_value<T>(supply: &Supply<T>): u64 \{
-    supply.value
-}
-
- - - -
- - - -## Function `create_supply` - -Create a new supply for type T. - - -

-public fun create_supply<T: drop>(_: T): balance::Supply<T>
-
- - - -
-Implementation - - -

-public fun create_supply<T: drop>(_: T): Supply<T> \{
-    Supply \{ value: 0 }
-}
-
- - - -
- - - -## Function `increase_supply` - -Increase supply by -value and create a new -Balance<T> with this value. - - -

-public fun increase_supply<T>(self: &mut balance::Supply<T>, value: u64): balance::Balance<T>
-
- - - -
-Implementation - - -

-public fun increase_supply<T>(self: &mut Supply<T>, value: u64): Balance<T> \{
-    assert!(value < (18446744073709551615u64 - self.value), EOverflow);
-    self.value = self.value + value;
-    Balance \{ value }
-}
-
- - - -
- - - -## Function `decrease_supply` - -Burn a `Balance` and decrease `Supply`. - - -

-public fun decrease_supply<T>(self: &mut balance::Supply<T>, balance: balance::Balance<T>): u64
-
- - - -
-Implementation - - -

-public fun decrease_supply<T>(self: &mut Supply<T>, balance: Balance<T>): u64 \{
-    let Balance \{ value } = balance;
-    assert!(self.value >= value, EOverflow);
-    self.value = self.value - value;
-    value
-}
-
- - - -
- - - -## Function `zero` - -Create a zero -Balance for type -T. - - -

-public fun zero<T>(): balance::Balance<T>
-
- - - -
-Implementation - - -

-public fun zero<T>(): Balance<T> \{
-    Balance \{ value: 0 }
-}
-
- - - -
- - - -## Function `join` - -Join two balances together. - - -

-public fun join<T>(self: &mut balance::Balance<T>, balance: balance::Balance<T>): u64
-
- - - -
-Implementation - - -

-public fun join<T>(self: &mut Balance<T>, balance: Balance<T>): u64 \{
-    let Balance \{ value } = balance;
-    self.value = self.value + value;
-    self.value
-}
-
- - - -
- - - -## Function `split` - -Split a -Balance and take a sub balance from it. - - -

-public fun split<T>(self: &mut balance::Balance<T>, value: u64): balance::Balance<T>
-
- - - -
-Implementation - - -

-public fun split<T>(self: &mut Balance<T>, value: u64): Balance<T> \{
-    assert!(self.value >= value, ENotEnough);
-    self.value = self.value - value;
-    Balance \{ value }
-}
-
- - - -
- - - -## Function `withdraw_all` - -Withdraw all balance. After this the remaining balance must be 0. - - -

-public fun withdraw_all<T>(self: &mut balance::Balance<T>): balance::Balance<T>
-
- - - -
-Implementation - - -

-public fun withdraw_all<T>(self: &mut Balance<T>): Balance<T> \{
-    let value = self.value;
-    split(self, value)
-}
-
- - - -
- - - -## Function `destroy_zero` - -Destroy a zero -Balance. - - -

-public fun destroy_zero<T>(balance: balance::Balance<T>)
-
- - - -
-Implementation - - -

-public fun destroy_zero<T>(balance: Balance<T>) \{
-    assert!(balance.value == 0, ENonZero);
-    let Balance \{ value: _ } = balance;
-}
-
- - - -
- - - -## Function `create_staking_rewards` - -CAUTION: this function creates a -Balance without increasing the supply. -It should only be called by the epoch change system txn to create staking rewards, -and nowhere else. - - -

-fun create_staking_rewards<T>(value: u64, ctx: &tx_context::TxContext): balance::Balance<T>
-
- - - -
-Implementation - - -

-fun create_staking_rewards<T>(value: u64, ctx: &TxContext): Balance<T> \{
-    assert!(ctx.sender() == @0x0, ENotSystemAddress);
-    Balance \{ value }
-}
-
- - - -
- - - -## Function `destroy_storage_rebates` - -CAUTION: this function destroys a -Balance without decreasing the supply. -It should only be called by the epoch change system txn to destroy storage rebates, -and nowhere else. - - -

-fun destroy_storage_rebates<T>(self: balance::Balance<T>, ctx: &tx_context::TxContext)
-
- - - -
-Implementation - - -

-fun destroy_storage_rebates<T>(self: Balance<T>, ctx: &TxContext) \{
-    assert!(ctx.sender() == @0x0, ENotSystemAddress);
-    let Balance \{ value: _ } = self;
-}
-
- - - -
- - - -## Function `destroy_genesis_supply` - -CAUTION: this function destroys a -Balance without decreasing the supply. -It should only be called by the genesis txn to destroy parts of the IOTA supply -which was created during the migration and for no other reason. - - -

-fun destroy_genesis_supply<T>(self: balance::Balance<T>, ctx: &tx_context::TxContext)
-
- - - -
-Implementation - - -

-fun destroy_genesis_supply<T>(self: Balance<T>, ctx: &TxContext) \{
-    assert!(ctx.sender() == @0x0, ENotSystemAddress);
-    assert!(ctx.epoch() == 0, ENotGenesisEpoch);
-
-    let Balance \{ value: _ } = self;
-}
-
- - - -
- - - -## Function `destroy_supply` - -Destroy a -Supply preventing any further minting and burning. - - -

-public(friend) fun destroy_supply<T>(self: balance::Supply<T>): u64
-
- - - -
-Implementation - - -

-public(package) fun destroy_supply<T>(self: Supply<T>): u64 \{
-    let Supply \{ value } = self;
-    value
-}
-
- - - -
diff --git a/crates/iota-framework/docs/iota-framework/bcs.mdx b/crates/iota-framework/docs/iota-framework/bcs.mdx deleted file mode 100644 index 3c7a5ab23c0..00000000000 --- a/crates/iota-framework/docs/iota-framework/bcs.mdx +++ /dev/null @@ -1,844 +0,0 @@ ---- -title: Module `0x2::bcs` ---- -import Link from '@docusaurus/Link'; - - -This module implements BCS (de)serialization in Move. -Full specification can be found here: https://github.com/diem/bcs - -Short summary (for Move-supported types): - -- address - sequence of X bytes -- bool - byte with 0 or 1 -- u8 - a single u8 byte -- u64 / u128 / u256 - LE bytes -- vector - ULEB128 length + LEN elements -- option - first byte bool: None (0) or Some (1), then value - -Usage example: -``` -/// This function reads u8 and u64 value from the input -/// and returns the rest of the bytes. -fun deserialize(bytes: vector): (u8, u64, vector) { -use iota::bcs::{Self, BCS}; - -let prepared: BCS = bcs::new(bytes); -let (u8_value, u64_value) = ( -prepared.peel_u8(), -prepared.peel_u64() -); - -// unpack bcs struct -let leftovers = prepared.into_remainder_bytes(); - -(u8_value, u64_value, leftovers) -} -``` - - -- [Struct `BCS`](#0x2_bcs_BCS) -- [Constants](#@Constants_0) -- [Function `to_bytes`](#0x2_bcs_to_bytes) -- [Function `new`](#0x2_bcs_new) -- [Function `into_remainder_bytes`](#0x2_bcs_into_remainder_bytes) -- [Function `peel_address`](#0x2_bcs_peel_address) -- [Function `peel_bool`](#0x2_bcs_peel_bool) -- [Function `peel_u8`](#0x2_bcs_peel_u8) -- [Function `peel_u64`](#0x2_bcs_peel_u64) -- [Function `peel_u128`](#0x2_bcs_peel_u128) -- [Function `peel_u256`](#0x2_bcs_peel_u256) -- [Function `peel_vec_length`](#0x2_bcs_peel_vec_length) -- [Function `peel_vec_address`](#0x2_bcs_peel_vec_address) -- [Function `peel_vec_bool`](#0x2_bcs_peel_vec_bool) -- [Function `peel_vec_u8`](#0x2_bcs_peel_vec_u8) -- [Function `peel_vec_vec_u8`](#0x2_bcs_peel_vec_vec_u8) -- [Function `peel_vec_u64`](#0x2_bcs_peel_vec_u64) -- [Function `peel_vec_u128`](#0x2_bcs_peel_vec_u128) -- [Function `peel_option_address`](#0x2_bcs_peel_option_address) -- [Function `peel_option_bool`](#0x2_bcs_peel_option_bool) -- [Function `peel_option_u8`](#0x2_bcs_peel_option_u8) -- [Function `peel_option_u64`](#0x2_bcs_peel_option_u64) -- [Function `peel_option_u128`](#0x2_bcs_peel_option_u128) - - -

-use 0x1::bcs;
-use 0x1::option;
-use 0x1::vector;
-use 0x2::address;
-
- - - - - -## Struct `BCS` - -A helper struct that saves resources on operations. For better -vector performance, it stores reversed bytes of the BCS and -enables use of -vector::pop_back. - - -

-struct BCS has copy, drop, store
-
- - - -
-Fields - - -
-
- -bytes: vector<u8> -
-
- -
-
- - -
- - - -## Constants - - - - -For when ULEB byte is out of range (or not found). - - -

-const ELenOutOfRange: u64 = 2;
-
- - - - - -For when the boolean value different than -0 or -1. - - -

-const ENotBool: u64 = 1;
-
- - - - - -For when bytes length is less than required for deserialization. - - -

-const EOutOfRange: u64 = 0;
-
- - - - - -## Function `to_bytes` - -Get BCS serialized bytes for any value. -Re-exports stdlib -bcs::to_bytes. - - -

-public fun to_bytes<T>(value: &T): vector<u8>
-
- - - -
-Implementation - - -

-public fun to_bytes<T>(value: &T): vector<u8> \{
-    bcs::to_bytes(value)
-}
-
- - - -
- - - -## Function `new` - -Creates a new instance of BCS wrapper that holds inversed -bytes for better performance. - - -

-public fun new(bytes: vector<u8>): bcs::BCS
-
- - - -
-Implementation - - -

-public fun new(mut bytes: vector<u8>): BCS \{
-    bytes.reverse();
-    BCS \{ bytes }
-}
-
- - - -
- - - -## Function `into_remainder_bytes` - -Unpack the -BCS struct returning the leftover bytes. -Useful for passing the data further after partial deserialization. - - -

-public fun into_remainder_bytes(bcs: bcs::BCS): vector<u8>
-
- - - -
-Implementation - - -

-public fun into_remainder_bytes(bcs: BCS): vector<u8> \{
-    let BCS \{ mut bytes } = bcs;
-    bytes.reverse();
-    bytes
-}
-
- - - -
- - - -## Function `peel_address` - -Read address from the bcs-serialized bytes. - - -

-public fun peel_address(bcs: &mut bcs::BCS): address
-
- - - -
-Implementation - - -

-public fun peel_address(bcs: &mut BCS): address \{
-    assert!(bcs.bytes.length() >= address::length(), EOutOfRange);
-    let (mut addr_bytes, mut i) = (vector[], 0);
-    while (i < address::length()) \{
-        addr_bytes.push_back(bcs.bytes.pop_back());
-        i = i + 1;
-    };
-    address::from_bytes(addr_bytes)
-}
-
- - - -
- - - -## Function `peel_bool` - -Read a -bool value from bcs-serialized bytes. - - -

-public fun peel_bool(bcs: &mut bcs::BCS): bool
-
- - - -
-Implementation - - -

-public fun peel_bool(bcs: &mut BCS): bool \{
-    let value = bcs.peel_u8();
-    if (value == 0) \{
-        false
-    } else if (value == 1) \{
-        true
-    } else \{
-        abort ENotBool
-    }
-}
-
- - - -
- - - -## Function `peel_u8` - -Read -u8 value from bcs-serialized bytes. - - -

-public fun peel_u8(bcs: &mut bcs::BCS): u8
-
- - - -
-Implementation - - -

-public fun peel_u8(bcs: &mut BCS): u8 \{
-    assert!(bcs.bytes.length() >= 1, EOutOfRange);
-    bcs.bytes.pop_back()
-}
-
- - - -
- - - -## Function `peel_u64` - -Read -u64 value from bcs-serialized bytes. - - -

-public fun peel_u64(bcs: &mut bcs::BCS): u64
-
- - - -
-Implementation - - -

-public fun peel_u64(bcs: &mut BCS): u64 \{
-    assert!(bcs.bytes.length() >= 8, EOutOfRange);
-
-    let (mut value, mut i) = (0u64, 0u8);
-    while (i < 64) \{
-        let byte = bcs.bytes.pop_back() as u64;
-        value = value + (byte << i);
-        i = i + 8;
-    };
-
-    value
-}
-
- - - -
- - - -## Function `peel_u128` - -Read -u128 value from bcs-serialized bytes. - - -

-public fun peel_u128(bcs: &mut bcs::BCS): u128
-
- - - -
-Implementation - - -

-public fun peel_u128(bcs: &mut BCS): u128 \{
-    assert!(bcs.bytes.length() >= 16, EOutOfRange);
-
-    let (mut value, mut i) = (0u128, 0u8);
-    while (i < 128) \{
-        let byte = bcs.bytes.pop_back() as u128;
-        value = value + (byte << i);
-        i = i + 8;
-    };
-
-    value
-}
-
- - - -
- - - -## Function `peel_u256` - -Read -u256 value from bcs-serialized bytes. - - -

-public fun peel_u256(bcs: &mut bcs::BCS): u256
-
- - - -
-Implementation - - -

-public fun peel_u256(bcs: &mut BCS): u256 \{
-    assert!(bcs.bytes.length() >= 32, EOutOfRange);
-
-    let (mut value, mut i) = (0u256, 0u16);
-    while (i < 256) \{
-        let byte = bcs.bytes.pop_back() as u256;
-        value = value + (byte << (i as u8));
-        i = i + 8;
-    };
-
-    value
-}
-
- - - -
- - - -## Function `peel_vec_length` - -Read ULEB bytes expecting a vector length. Result should -then be used to perform -peel_* operation LEN times. - -In BCS -vector length is implemented with ULEB128; -See more here: https://en.wikipedia.org/wiki/LEB128 - - -

-public fun peel_vec_length(bcs: &mut bcs::BCS): u64
-
- - - -
-Implementation - - -

-public fun peel_vec_length(bcs: &mut BCS): u64 \{
-    let (mut total, mut shift, mut len) = (0u64, 0, 0);
-    while (true) \{
-        assert!(len <= 4, ELenOutOfRange);
-        let byte = bcs.bytes.pop_back() as u64;
-        len = len + 1;
-        total = total | ((byte & 0x7f) << shift);
-        if ((byte & 0x80) == 0) \{
-            break
-        };
-        shift = shift + 7;
-    };
-    total
-}
-
- - - -
- - - -## Function `peel_vec_address` - -Peel a vector of -address from serialized bytes. - - -

-public fun peel_vec_address(bcs: &mut bcs::BCS): vector<address>
-
- - - -
-Implementation - - -

-public fun peel_vec_address(bcs: &mut BCS): vector<address> \{
-    let (len, mut i, mut res) = (bcs.peel_vec_length(), 0, vector[]);
-    while (i < len) \{
-        res.push_back(bcs.peel_address());
-        i = i + 1;
-    };
-    res
-}
-
- - - -
- - - -## Function `peel_vec_bool` - -Peel a vector of -address from serialized bytes. - - -

-public fun peel_vec_bool(bcs: &mut bcs::BCS): vector<bool>
-
- - - -
-Implementation - - -

-public fun peel_vec_bool(bcs: &mut BCS): vector<bool> \{
-    let (len, mut i, mut res) = (bcs.peel_vec_length(), 0, vector[]);
-    while (i < len) \{
-        res.push_back(bcs.peel_bool());
-        i = i + 1;
-    };
-    res
-}
-
- - - -
- - - -## Function `peel_vec_u8` - -Peel a vector of -u8 (eg string) from serialized bytes. - - -

-public fun peel_vec_u8(bcs: &mut bcs::BCS): vector<u8>
-
- - - -
-Implementation - - -

-public fun peel_vec_u8(bcs: &mut BCS): vector<u8> \{
-    let (len, mut i, mut res) = (bcs.peel_vec_length(), 0, vector[]);
-    while (i < len) \{
-        res.push_back(bcs.peel_u8());
-        i = i + 1;
-    };
-    res
-}
-
- - - -
- - - -## Function `peel_vec_vec_u8` - -Peel a -vector<vector<u8>> (eg vec of string) from serialized bytes. - - -

-public fun peel_vec_vec_u8(bcs: &mut bcs::BCS): vector<vector<u8>>
-
- - - -
-Implementation - - -

-public fun peel_vec_vec_u8(bcs: &mut BCS): vector<vector<u8>> \{
-    let (len, mut i, mut res) = (bcs.peel_vec_length(), 0, vector[]);
-    while (i < len) \{
-        res.push_back(bcs.peel_vec_u8());
-        i = i + 1;
-    };
-    res
-}
-
- - - -
- - - -## Function `peel_vec_u64` - -Peel a vector of -u64 from serialized bytes. - - -

-public fun peel_vec_u64(bcs: &mut bcs::BCS): vector<u64>
-
- - - -
-Implementation - - -

-public fun peel_vec_u64(bcs: &mut BCS): vector<u64> \{
-    let (len, mut i, mut res) = (bcs.peel_vec_length(), 0, vector[]);
-    while (i < len) \{
-        res.push_back(bcs.peel_u64());
-        i = i + 1;
-    };
-    res
-}
-
- - - -
- - - -## Function `peel_vec_u128` - -Peel a vector of -u128 from serialized bytes. - - -

-public fun peel_vec_u128(bcs: &mut bcs::BCS): vector<u128>
-
- - - -
-Implementation - - -

-public fun peel_vec_u128(bcs: &mut BCS): vector<u128> \{
-    let (len, mut i, mut res) = (bcs.peel_vec_length(), 0, vector[]);
-    while (i < len) \{
-        res.push_back(bcs.peel_u128());
-        i = i + 1;
-    };
-    res
-}
-
- - - -
- - - -## Function `peel_option_address` - -Peel -Option<address> from serialized bytes. - - -

-public fun peel_option_address(bcs: &mut bcs::BCS): option::Option<address>
-
- - - -
-Implementation - - -

-public fun peel_option_address(bcs: &mut BCS): Option<address> \{
-    if (bcs.peel_bool()) \{
-        option::some(bcs.peel_address())
-    } else \{
-        option::none()
-    }
-}
-
- - - -
- - - -## Function `peel_option_bool` - -Peel -Option<bool> from serialized bytes. - - -

-public fun peel_option_bool(bcs: &mut bcs::BCS): option::Option<bool>
-
- - - -
-Implementation - - -

-public fun peel_option_bool(bcs: &mut BCS): Option<bool> \{
-    if (bcs.peel_bool()) \{
-        option::some(bcs.peel_bool())
-    } else \{
-        option::none()
-    }
-}
-
- - - -
- - - -## Function `peel_option_u8` - -Peel -Option<u8> from serialized bytes. - - -

-public fun peel_option_u8(bcs: &mut bcs::BCS): option::Option<u8>
-
- - - -
-Implementation - - -

-public fun peel_option_u8(bcs: &mut BCS): Option<u8> \{
-    if (bcs.peel_bool()) \{
-        option::some(bcs.peel_u8())
-    } else \{
-        option::none()
-    }
-}
-
- - - -
- - - -## Function `peel_option_u64` - -Peel -Option<u64> from serialized bytes. - - -

-public fun peel_option_u64(bcs: &mut bcs::BCS): option::Option<u64>
-
- - - -
-Implementation - - -

-public fun peel_option_u64(bcs: &mut BCS): Option<u64> \{
-    if (bcs.peel_bool()) \{
-        option::some(bcs.peel_u64())
-    } else \{
-        option::none()
-    }
-}
-
- - - -
- - - -## Function `peel_option_u128` - -Peel -Option<u128> from serialized bytes. - - -

-public fun peel_option_u128(bcs: &mut bcs::BCS): option::Option<u128>
-
- - - -
-Implementation - - -

-public fun peel_option_u128(bcs: &mut BCS): Option<u128> \{
-    if (bcs.peel_bool()) \{
-        option::some(bcs.peel_u128())
-    } else \{
-        option::none()
-    }
-}
-
- - - -
diff --git a/crates/iota-framework/docs/iota-framework/bls12381.mdx b/crates/iota-framework/docs/iota-framework/bls12381.mdx deleted file mode 100644 index 1cf97a57f67..00000000000 --- a/crates/iota-framework/docs/iota-framework/bls12381.mdx +++ /dev/null @@ -1,1374 +0,0 @@ ---- -title: Module `0x2::bls12381` ---- -import Link from '@docusaurus/Link'; - - -Group operations of BLS12-381. - - -- [Struct `Scalar`](#0x2_bls12381_Scalar) -- [Struct `G1`](#0x2_bls12381_G1) -- [Struct `G2`](#0x2_bls12381_G2) -- [Struct `GT`](#0x2_bls12381_GT) -- [Constants](#@Constants_0) -- [Function `bls12381_min_sig_verify`](#0x2_bls12381_bls12381_min_sig_verify) -- [Function `bls12381_min_pk_verify`](#0x2_bls12381_bls12381_min_pk_verify) -- [Function `scalar_from_bytes`](#0x2_bls12381_scalar_from_bytes) -- [Function `scalar_from_u64`](#0x2_bls12381_scalar_from_u64) -- [Function `scalar_zero`](#0x2_bls12381_scalar_zero) -- [Function `scalar_one`](#0x2_bls12381_scalar_one) -- [Function `scalar_add`](#0x2_bls12381_scalar_add) -- [Function `scalar_sub`](#0x2_bls12381_scalar_sub) -- [Function `scalar_mul`](#0x2_bls12381_scalar_mul) -- [Function `scalar_div`](#0x2_bls12381_scalar_div) -- [Function `scalar_neg`](#0x2_bls12381_scalar_neg) -- [Function `scalar_inv`](#0x2_bls12381_scalar_inv) -- [Function `g1_from_bytes`](#0x2_bls12381_g1_from_bytes) -- [Function `g1_identity`](#0x2_bls12381_g1_identity) -- [Function `g1_generator`](#0x2_bls12381_g1_generator) -- [Function `g1_add`](#0x2_bls12381_g1_add) -- [Function `g1_sub`](#0x2_bls12381_g1_sub) -- [Function `g1_mul`](#0x2_bls12381_g1_mul) -- [Function `g1_div`](#0x2_bls12381_g1_div) -- [Function `g1_neg`](#0x2_bls12381_g1_neg) -- [Function `hash_to_g1`](#0x2_bls12381_hash_to_g1) -- [Function `g1_multi_scalar_multiplication`](#0x2_bls12381_g1_multi_scalar_multiplication) -- [Function `g2_from_bytes`](#0x2_bls12381_g2_from_bytes) -- [Function `g2_identity`](#0x2_bls12381_g2_identity) -- [Function `g2_generator`](#0x2_bls12381_g2_generator) -- [Function `g2_add`](#0x2_bls12381_g2_add) -- [Function `g2_sub`](#0x2_bls12381_g2_sub) -- [Function `g2_mul`](#0x2_bls12381_g2_mul) -- [Function `g2_div`](#0x2_bls12381_g2_div) -- [Function `g2_neg`](#0x2_bls12381_g2_neg) -- [Function `hash_to_g2`](#0x2_bls12381_hash_to_g2) -- [Function `g2_multi_scalar_multiplication`](#0x2_bls12381_g2_multi_scalar_multiplication) -- [Function `gt_identity`](#0x2_bls12381_gt_identity) -- [Function `gt_generator`](#0x2_bls12381_gt_generator) -- [Function `gt_add`](#0x2_bls12381_gt_add) -- [Function `gt_sub`](#0x2_bls12381_gt_sub) -- [Function `gt_mul`](#0x2_bls12381_gt_mul) -- [Function `gt_div`](#0x2_bls12381_gt_div) -- [Function `gt_neg`](#0x2_bls12381_gt_neg) -- [Function `pairing`](#0x2_bls12381_pairing) - - -

-use 0x2::group_ops;
-
- - - - - -## Struct `Scalar` - - - -

-struct Scalar
-
- - - -
-Fields - - -
-
- -dummy_field: bool -
-
- -
-
- - -
- - - -## Struct `G1` - - - -

-struct G1
-
- - - -
-Fields - - -
-
- -dummy_field: bool -
-
- -
-
- - -
- - - -## Struct `G2` - - - -

-struct G2
-
- - - -
-Fields - - -
-
- -dummy_field: bool -
-
- -
-
- - -
- - - -## Struct `GT` - - - -

-struct GT
-
- - - -
-Fields - - -
-
- -dummy_field: bool -
-
- -
-
- - -
- - - -## Constants - - - - - - -

-const G1_GENERATOR_BYTES: vector<u8> = [151, 241, 211, 167, 49, 151, 215, 148, 38, 149, 99, 140, 79, 169, 172, 15, 195, 104, 140, 79, 151, 116, 185, 5, 161, 78, 58, 63, 23, 27, 172, 88, 108, 85, 232, 63, 249, 122, 26, 239, 251, 58, 240, 10, 219, 34, 198, 187];
-
- - - - - - - -

-const G1_IDENTITY_BYTES: vector<u8> = [192, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
-
- - - - - - - -

-const G1_TYPE: u8 = 1;
-
- - - - - - - -

-const G2_GENERATOR_BYTES: vector<u8> = [147, 224, 43, 96, 82, 113, 159, 96, 125, 172, 211, 160, 136, 39, 79, 101, 89, 107, 208, 208, 153, 32, 182, 26, 181, 218, 97, 187, 220, 127, 80, 73, 51, 76, 241, 18, 19, 148, 93, 87, 229, 172, 125, 5, 93, 4, 43, 126, 2, 74, 162, 178, 240, 143, 10, 145, 38, 8, 5, 39, 45, 197, 16, 81, 198, 228, 122, 212, 250, 64, 59, 2, 180, 81, 11, 100, 122, 227, 209, 119, 11, 172, 3, 38, 168, 5, 187, 239, 212, 128, 86, 200, 193, 33, 189, 184];
-
- - - - - - - -

-const G2_IDENTITY_BYTES: vector<u8> = [192, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
-
- - - - - - - -

-const G2_TYPE: u8 = 2;
-
- - - - - - - -

-const GT_GENERATOR_BYTES: vector<u8> = [18, 80, 235, 216, 113, 252, 10, 146, 167, 178, 216, 49, 104, 208, 215, 39, 39, 45, 68, 27, 239, 161, 92, 80, 61, 216, 233, 12, 233, 141, 179, 231, 182, 209, 148, 246, 8, 57, 197, 8, 168, 67, 5, 170, 202, 23, 137, 182, 8, 154, 28, 91, 70, 229, 17, 11, 134, 117, 14, 198, 165, 50, 52, 136, 104, 168, 64, 69, 72, 60, 146, 183, 175, 90, 246, 137, 69, 46, 175, 171, 241, 168, 148, 62, 80, 67, 159, 29, 89, 136, 42, 152, 234, 160, 23, 15, 25, 242, 99, 55, 210, 5, 251, 70, 156, 214, 189, 21, 195, 213, 160, 77, 200, 135, 132, 251, 179, 208, 178, 219, 222, 165, 77, 67, 178, 183, 63, 44, 187, 18, 213, 131, 134, 168, 112, 62, 15, 148, 130, 38, 228, 126, 232, 157, 6, 251, 162, 62, 183, 197, 175, 13, 159, 128, 148, 12, 167, 113, 182, 255, 213, 133, 123, 170, 242, 34, 235, 149, 167, 210, 128, 157, 97, 191, 224, 46, 27, 253, 27, 104, 255, 2, 240, 184, 16, 42, 225, 194, 213, 213, 171, 26, 19, 104, 187, 68, 92, 124, 45, 32, 151, 3, 242, 57, 104, 156, 227, 76, 3, 120, 166, 142, 114, 166, 179, 178, 22, 218, 14, 34, 165, 3, 27, 84, 221, 255, 87, 48, 147, 150, 179, 140, 136, 28, 76, 132, 158, 194, 62, 135, 25, 53, 2, 184, 110, 219, 136, 87, 194, 115, 250, 7, 90, 80, 81, 41, 55, 224, 121, 78, 30, 101, 167, 97, 124, 144, 216, 189, 102, 6, 91, 31, 255, 229, 29, 122, 87, 153, 115, 177, 49, 80, 33, 236, 60, 25, 147, 79, 17, 184, 180, 36, 205, 72, 191, 56, 252, 239, 104, 8, 59, 11, 14, 197, 200, 26, 147, 179, 48, 238, 26, 103, 125, 13, 21, 255, 123, 152, 78, 137, 120, 239, 72, 136, 30, 50, 250, 201, 27, 147, 180, 115, 51, 226, 186, 87, 3, 53, 15, 85, 167, 174, 252, 211, 195, 27, 79, 203, 108, 229, 119, 28, 198, 160, 233, 120, 106, 181, 151, 51, 32, 200, 6, 173, 54, 8, 41, 16, 123, 168, 16, 197, 160, 159, 253, 217, 190, 34, 145, 160, 194, 90, 153, 162, 1, 178, 245, 34, 71, 61, 23, 19, 145, 18, 91, 168, 77, 196, 0, 124, 251, 242, 248, 218, 117, 47, 124, 116, 24, 82, 3, 252, 202, 88, 154, 199, 25, 195, 77, 255, 187, 170, 216, 67, 29, 173, 28, 31, 181, 151, 170, 165, 1, 129, 7, 21, 79, 37, 167, 100, 189, 60, 121, 147, 122, 69, 184, 69, 70, 218, 99, 75, 143, 107, 225, 74, 128, 97, 229, 92, 206, 186, 71, 139, 35, 247, 218, 202, 163, 92, 140, 167, 139, 234, 233, 98, 64, 69, 180, 182, 4, 197, 129, 35, 77, 8, 106, 153, 2, 36, 155, 100, 114, 143, 253, 33, 161, 137, 232, 121, 53, 169, 84, 5, 28, 124, 219, 167, 179, 135, 38, 41, 164, 250, 252, 5, 6, 98, 69, 203, 145, 8, 240, 36, 45, 15, 227, 239, 15, 65, 229, 134, 99, 191, 8, 207, 6, 134, 114, 203, 208, 26, 126, 199, 59, 172, 164, 215, 44, 169, 53, 68, 222, 255, 104, 107, 253, 109, 245, 67, 212, 142, 170, 36, 175, 228, 126, 30, 253, 228, 73, 56, 59, 103, 102, 49];
-
- - - - - - - -

-const GT_IDENTITY_BYTES: vector<u8> = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
-
- - - - - - - -

-const GT_TYPE: u8 = 3;
-
- - - - - - - -

-const SCALAR_ONE_BYTES: vector<u8> = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1];
-
- - - - - - - -

-const SCALAR_TYPE: u8 = 0;
-
- - - - - - - -

-const SCALAR_ZERO_BYTES: vector<u8> = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
-
- - - - - -## Function `bls12381_min_sig_verify` - -@param signature: A 48-bytes signature that is a point on the G1 subgroup. -@param public_key: A 96-bytes public key that is a point on the G2 subgroup. -@param msg: The message that we test the signature against. - -If the signature is a valid signature of the message and public key according to -BLS_SIG_BLS12381G1_XMD:SHA-256_SSWU_RO_NUL_, return true. Otherwise, return false. - - -

-public fun bls12381_min_sig_verify(signature: &vector<u8>, public_key: &vector<u8>, msg: &vector<u8>): bool
-
- - - -
-Implementation - - -

-public native fun bls12381_min_sig_verify(signature: &vector<u8>, public_key: &vector<u8>, msg: &vector<u8>): bool;
-
- - - -
- - - -## Function `bls12381_min_pk_verify` - -@param signature: A 96-bytes signature that is a point on the G2 subgroup. -@param public_key: A 48-bytes public key that is a point on the G1 subgroup. -@param msg: The message that we test the signature against. - -If the signature is a valid signature of the message and public key according to -BLS_SIG_BLS12381G2_XMD:SHA-256_SSWU_RO_NUL_, return true. Otherwise, return false. - - -

-public fun bls12381_min_pk_verify(signature: &vector<u8>, public_key: &vector<u8>, msg: &vector<u8>): bool
-
- - - -
-Implementation - - -

-public native fun bls12381_min_pk_verify(signature: &vector<u8>, public_key: &vector<u8>, msg: &vector<u8>): bool;
-
- - - -
- - - -## Function `scalar_from_bytes` - - - -

-public fun scalar_from_bytes(bytes: &vector<u8>): group_ops::Element<bls12381::Scalar>
-
- - - -
-Implementation - - -

-public fun scalar_from_bytes(bytes: &vector<u8>): Element<Scalar> \{
-    group_ops::from_bytes(SCALAR_TYPE, bytes, false)
-}
-
- - - -
- - - -## Function `scalar_from_u64` - - - -

-public fun scalar_from_u64(x: u64): group_ops::Element<bls12381::Scalar>
-
- - - -
-Implementation - - -

-public fun scalar_from_u64(x: u64): Element<Scalar> \{
-    let mut bytes = SCALAR_ZERO_BYTES;
-    group_ops::set_as_prefix(x, true, &mut bytes);
-    group_ops::from_bytes(SCALAR_TYPE, &bytes, true)
-}
-
- - - -
- - - -## Function `scalar_zero` - - - -

-public fun scalar_zero(): group_ops::Element<bls12381::Scalar>
-
- - - -
-Implementation - - -

-public fun scalar_zero(): Element<Scalar> \{
-    let zero = SCALAR_ZERO_BYTES;
-    group_ops::from_bytes(SCALAR_TYPE, &zero, true)
-}
-
- - - -
- - - -## Function `scalar_one` - - - -

-public fun scalar_one(): group_ops::Element<bls12381::Scalar>
-
- - - -
-Implementation - - -

-public fun scalar_one(): Element<Scalar> \{
-    let one = SCALAR_ONE_BYTES;
-    group_ops::from_bytes(SCALAR_TYPE, &one, true)
-}
-
- - - -
- - - -## Function `scalar_add` - - - -

-public fun scalar_add(e1: &group_ops::Element<bls12381::Scalar>, e2: &group_ops::Element<bls12381::Scalar>): group_ops::Element<bls12381::Scalar>
-
- - - -
-Implementation - - -

-public fun scalar_add(e1: &Element<Scalar>, e2: &Element<Scalar>): Element<Scalar> \{
-    group_ops::add(SCALAR_TYPE, e1, e2)
-}
-
- - - -
- - - -## Function `scalar_sub` - - - -

-public fun scalar_sub(e1: &group_ops::Element<bls12381::Scalar>, e2: &group_ops::Element<bls12381::Scalar>): group_ops::Element<bls12381::Scalar>
-
- - - -
-Implementation - - -

-public fun scalar_sub(e1: &Element<Scalar>, e2: &Element<Scalar>): Element<Scalar> \{
-    group_ops::sub(SCALAR_TYPE, e1, e2)
-}
-
- - - -
- - - -## Function `scalar_mul` - - - -

-public fun scalar_mul(e1: &group_ops::Element<bls12381::Scalar>, e2: &group_ops::Element<bls12381::Scalar>): group_ops::Element<bls12381::Scalar>
-
- - - -
-Implementation - - -

-public fun scalar_mul(e1: &Element<Scalar>, e2: &Element<Scalar>): Element<Scalar> \{
-    group_ops::mul(SCALAR_TYPE, e1, e2)
-}
-
- - - -
- - - -## Function `scalar_div` - -Returns e2/e1, fails if a is zero. - - -

-public fun scalar_div(e1: &group_ops::Element<bls12381::Scalar>, e2: &group_ops::Element<bls12381::Scalar>): group_ops::Element<bls12381::Scalar>
-
- - - -
-Implementation - - -

-public fun scalar_div(e1: &Element<Scalar>, e2: &Element<Scalar>): Element<Scalar> \{
-    group_ops::div(SCALAR_TYPE, e1, e2)
-}
-
- - - -
- - - -## Function `scalar_neg` - - - -

-public fun scalar_neg(e: &group_ops::Element<bls12381::Scalar>): group_ops::Element<bls12381::Scalar>
-
- - - -
-Implementation - - -

-public fun scalar_neg(e: &Element<Scalar>): Element<Scalar> \{
-    scalar_sub(&scalar_zero(), e)
-}
-
- - - -
- - - -## Function `scalar_inv` - - - -

-public fun scalar_inv(e: &group_ops::Element<bls12381::Scalar>): group_ops::Element<bls12381::Scalar>
-
- - - -
-Implementation - - -

-public fun scalar_inv(e: &Element<Scalar>): Element<Scalar> \{
-    scalar_div(e, &scalar_one())
-}
-
- - - -
- - - -## Function `g1_from_bytes` - - - -

-public fun g1_from_bytes(bytes: &vector<u8>): group_ops::Element<bls12381::G1>
-
- - - -
-Implementation - - -

-public fun g1_from_bytes(bytes: &vector<u8>): Element<G1> \{
-    group_ops::from_bytes(G1_TYPE, bytes, false)
-}
-
- - - -
- - - -## Function `g1_identity` - - - -

-public fun g1_identity(): group_ops::Element<bls12381::G1>
-
- - - -
-Implementation - - -

-public fun g1_identity(): Element<G1> \{
-    let identity = G1_IDENTITY_BYTES;
-    group_ops::from_bytes(G1_TYPE, &identity, true)
-}
-
- - - -
- - - -## Function `g1_generator` - - - -

-public fun g1_generator(): group_ops::Element<bls12381::G1>
-
- - - -
-Implementation - - -

-public fun g1_generator(): Element<G1> \{
-    let generator = G1_GENERATOR_BYTES;
-    group_ops::from_bytes(G1_TYPE, &generator, true)
-}
-
- - - -
- - - -## Function `g1_add` - - - -

-public fun g1_add(e1: &group_ops::Element<bls12381::G1>, e2: &group_ops::Element<bls12381::G1>): group_ops::Element<bls12381::G1>
-
- - - -
-Implementation - - -

-public fun g1_add(e1: &Element<G1>, e2: &Element<G1>): Element<G1> \{
-    group_ops::add(G1_TYPE, e1, e2)
-}
-
- - - -
- - - -## Function `g1_sub` - - - -

-public fun g1_sub(e1: &group_ops::Element<bls12381::G1>, e2: &group_ops::Element<bls12381::G1>): group_ops::Element<bls12381::G1>
-
- - - -
-Implementation - - -

-public fun g1_sub(e1: &Element<G1>, e2: &Element<G1>): Element<G1> \{
-    group_ops::sub(G1_TYPE, e1, e2)
-}
-
- - - -
- - - -## Function `g1_mul` - - - -

-public fun g1_mul(e1: &group_ops::Element<bls12381::Scalar>, e2: &group_ops::Element<bls12381::G1>): group_ops::Element<bls12381::G1>
-
- - - -
-Implementation - - -

-public fun g1_mul(e1: &Element<Scalar>, e2: &Element<G1>): Element<G1> \{
-    group_ops::mul(G1_TYPE, e1, e2)
-}
-
- - - -
- - - -## Function `g1_div` - -Returns e2 / e1, fails if scalar is zero. - - -

-public fun g1_div(e1: &group_ops::Element<bls12381::Scalar>, e2: &group_ops::Element<bls12381::G1>): group_ops::Element<bls12381::G1>
-
- - - -
-Implementation - - -

-public fun g1_div(e1: &Element<Scalar>, e2: &Element<G1>): Element<G1> \{
-    group_ops::div(G1_TYPE, e1, e2)
-}
-
- - - -
- - - -## Function `g1_neg` - - - -

-public fun g1_neg(e: &group_ops::Element<bls12381::G1>): group_ops::Element<bls12381::G1>
-
- - - -
-Implementation - - -

-public fun g1_neg(e: &Element<G1>): Element<G1> \{
-    g1_sub(&g1_identity(), e)
-}
-
- - - -
- - - -## Function `hash_to_g1` - -Hash using DST = BLS_SIG_BLS12381G1_XMD:SHA-256_SSWU_RO_NUL_ - - -

-public fun hash_to_g1(m: &vector<u8>): group_ops::Element<bls12381::G1>
-
- - - -
-Implementation - - -

-public fun hash_to_g1(m: &vector<u8>): Element<G1> \{
-    group_ops::hash_to(G1_TYPE, m)
-}
-
- - - -
- - - -## Function `g1_multi_scalar_multiplication` - -Let 'scalars' be the vector [s1, s2, ..., sn] and 'elements' be the vector [e1, e2, ..., en]. -Returns s1*e1 + s2*e2 + ... + sn*en. -Aborts with -EInputTooLong if the vectors are larger than 32 (may increase in the future). - - -

-public fun g1_multi_scalar_multiplication(scalars: &vector<group_ops::Element<bls12381::Scalar>>, elements: &vector<group_ops::Element<bls12381::G1>>): group_ops::Element<bls12381::G1>
-
- - - -
-Implementation - - -

-public fun g1_multi_scalar_multiplication(scalars: &vector<Element<Scalar>>, elements: &vector<Element<G1>>): Element<G1> \{
-    group_ops::multi_scalar_multiplication(G1_TYPE, scalars, elements)
-}
-
- - - -
- - - -## Function `g2_from_bytes` - - - -

-public fun g2_from_bytes(bytes: &vector<u8>): group_ops::Element<bls12381::G2>
-
- - - -
-Implementation - - -

-public fun g2_from_bytes(bytes: &vector<u8>): Element<G2> \{
-    group_ops::from_bytes(G2_TYPE, bytes, false)
-}
-
- - - -
- - - -## Function `g2_identity` - - - -

-public fun g2_identity(): group_ops::Element<bls12381::G2>
-
- - - -
-Implementation - - -

-public fun g2_identity(): Element<G2> \{
-    let identity = G2_IDENTITY_BYTES;
-    group_ops::from_bytes(G2_TYPE, &identity, true)
-}
-
- - - -
- - - -## Function `g2_generator` - - - -

-public fun g2_generator(): group_ops::Element<bls12381::G2>
-
- - - -
-Implementation - - -

-public fun g2_generator(): Element<G2> \{
-    let generator = G2_GENERATOR_BYTES;
-    group_ops::from_bytes(G2_TYPE, &generator, true)
-}
-
- - - -
- - - -## Function `g2_add` - - - -

-public fun g2_add(e1: &group_ops::Element<bls12381::G2>, e2: &group_ops::Element<bls12381::G2>): group_ops::Element<bls12381::G2>
-
- - - -
-Implementation - - -

-public fun g2_add(e1: &Element<G2>, e2: &Element<G2>): Element<G2> \{
-    group_ops::add(G2_TYPE, e1, e2)
-}
-
- - - -
- - - -## Function `g2_sub` - - - -

-public fun g2_sub(e1: &group_ops::Element<bls12381::G2>, e2: &group_ops::Element<bls12381::G2>): group_ops::Element<bls12381::G2>
-
- - - -
-Implementation - - -

-public fun g2_sub(e1: &Element<G2>, e2: &Element<G2>): Element<G2> \{
-    group_ops::sub(G2_TYPE, e1, e2)
-}
-
- - - -
- - - -## Function `g2_mul` - - - -

-public fun g2_mul(e1: &group_ops::Element<bls12381::Scalar>, e2: &group_ops::Element<bls12381::G2>): group_ops::Element<bls12381::G2>
-
- - - -
-Implementation - - -

-public fun g2_mul(e1: &Element<Scalar>, e2: &Element<G2>): Element<G2> \{
-    group_ops::mul(G2_TYPE, e1, e2)
-}
-
- - - -
- - - -## Function `g2_div` - -Returns e2 / e1, fails if scalar is zero. - - -

-public fun g2_div(e1: &group_ops::Element<bls12381::Scalar>, e2: &group_ops::Element<bls12381::G2>): group_ops::Element<bls12381::G2>
-
- - - -
-Implementation - - -

-public fun g2_div(e1: &Element<Scalar>, e2: &Element<G2>): Element<G2> \{
-    group_ops::div(G2_TYPE, e1, e2)
-}
-
- - - -
- - - -## Function `g2_neg` - - - -

-public fun g2_neg(e: &group_ops::Element<bls12381::G2>): group_ops::Element<bls12381::G2>
-
- - - -
-Implementation - - -

-public fun g2_neg(e: &Element<G2>): Element<G2> \{
-    g2_sub(&g2_identity(), e)
-}
-
- - - -
- - - -## Function `hash_to_g2` - -Hash using DST = BLS_SIG_BLS12381G2_XMD:SHA-256_SSWU_RO_NUL_ - - -

-public fun hash_to_g2(m: &vector<u8>): group_ops::Element<bls12381::G2>
-
- - - -
-Implementation - - -

-public fun hash_to_g2(m: &vector<u8>): Element<G2> \{
-    group_ops::hash_to(G2_TYPE, m)
-}
-
- - - -
- - - -## Function `g2_multi_scalar_multiplication` - -Let 'scalars' be the vector [s1, s2, ..., sn] and 'elements' be the vector [e1, e2, ..., en]. -Returns s1*e1 + s2*e2 + ... + sn*en. -Aborts with -EInputTooLong if the vectors are larger than 32 (may increase in the future). - - -

-public fun g2_multi_scalar_multiplication(scalars: &vector<group_ops::Element<bls12381::Scalar>>, elements: &vector<group_ops::Element<bls12381::G2>>): group_ops::Element<bls12381::G2>
-
- - - -
-Implementation - - -

-public fun g2_multi_scalar_multiplication(scalars: &vector<Element<Scalar>>, elements: &vector<Element<G2>>): Element<G2> \{
-    group_ops::multi_scalar_multiplication(G2_TYPE, scalars, elements)
-}
-
- - - -
- - - -## Function `gt_identity` - - - -

-public fun gt_identity(): group_ops::Element<bls12381::GT>
-
- - - -
-Implementation - - -

-public fun gt_identity(): Element<GT> \{
-    let identity = GT_IDENTITY_BYTES;
-    group_ops::from_bytes(GT_TYPE, &identity, true)
-}
-
- - - -
- - - -## Function `gt_generator` - - - -

-public fun gt_generator(): group_ops::Element<bls12381::GT>
-
- - - -
-Implementation - - -

-public fun gt_generator(): Element<GT> \{
-    let generator = GT_GENERATOR_BYTES;
-    group_ops::from_bytes(GT_TYPE, &generator, true)
-}
-
- - - -
- - - -## Function `gt_add` - - - -

-public fun gt_add(e1: &group_ops::Element<bls12381::GT>, e2: &group_ops::Element<bls12381::GT>): group_ops::Element<bls12381::GT>
-
- - - -
-Implementation - - -

-public fun gt_add(e1: &Element<GT>, e2: &Element<GT>): Element<GT> \{
-    group_ops::add(GT_TYPE, e1, e2)
-}
-
- - - -
- - - -## Function `gt_sub` - - - -

-public fun gt_sub(e1: &group_ops::Element<bls12381::GT>, e2: &group_ops::Element<bls12381::GT>): group_ops::Element<bls12381::GT>
-
- - - -
-Implementation - - -

-public fun gt_sub(e1: &Element<GT>, e2: &Element<GT>): Element<GT> \{
-    group_ops::sub(GT_TYPE, e1, e2)
-}
-
- - - -
- - - -## Function `gt_mul` - - - -

-public fun gt_mul(e1: &group_ops::Element<bls12381::Scalar>, e2: &group_ops::Element<bls12381::GT>): group_ops::Element<bls12381::GT>
-
- - - -
-Implementation - - -

-public fun gt_mul(e1: &Element<Scalar>, e2: &Element<GT>): Element<GT> \{
-    group_ops::mul(GT_TYPE, e1, e2)
-}
-
- - - -
- - - -## Function `gt_div` - -Returns e2 / e1, fails if scalar is zero. - - -

-public fun gt_div(e1: &group_ops::Element<bls12381::Scalar>, e2: &group_ops::Element<bls12381::GT>): group_ops::Element<bls12381::GT>
-
- - - -
-Implementation - - -

-public fun gt_div(e1: &Element<Scalar>, e2: &Element<GT>): Element<GT> \{
-    group_ops::div(GT_TYPE, e1, e2)
-}
-
- - - -
- - - -## Function `gt_neg` - - - -

-public fun gt_neg(e: &group_ops::Element<bls12381::GT>): group_ops::Element<bls12381::GT>
-
- - - -
-Implementation - - -

-public fun gt_neg(e: &Element<GT>): Element<GT> \{
-    gt_sub(&gt_identity(), e)
-}
-
- - - -
- - - -## Function `pairing` - - - -

-public fun pairing(e1: &group_ops::Element<bls12381::G1>, e2: &group_ops::Element<bls12381::G2>): group_ops::Element<bls12381::GT>
-
- - - -
-Implementation - - -

-public fun pairing(e1: &Element<G1>, e2: &Element<G2>): Element<GT> \{
-    group_ops::pairing(G1_TYPE, e1, e2)
-}
-
- - - -
diff --git a/crates/iota-framework/docs/iota-framework/borrow.mdx b/crates/iota-framework/docs/iota-framework/borrow.mdx deleted file mode 100644 index 5049641b29a..00000000000 --- a/crates/iota-framework/docs/iota-framework/borrow.mdx +++ /dev/null @@ -1,265 +0,0 @@ ---- -title: Module `0x2::borrow` ---- -import Link from '@docusaurus/Link'; - - -A simple library that enables hot-potato-locked borrow mechanics. - -With Programmable transactions, it is possible to borrow a value within -a transaction, use it and put back in the end. Hot-potato -Borrow makes -sure the object is returned and was not swapped for another one. - - -- [Struct `Referent`](#0x2_borrow_Referent) -- [Struct `Borrow`](#0x2_borrow_Borrow) -- [Constants](#@Constants_0) -- [Function `new`](#0x2_borrow_new) -- [Function `borrow`](#0x2_borrow_borrow) -- [Function `put_back`](#0x2_borrow_put_back) -- [Function `destroy`](#0x2_borrow_destroy) - - -

-use 0x1::option;
-use 0x2::object;
-use 0x2::tx_context;
-
- - - - - -## Struct `Referent` - -An object wrapping a -T and providing the borrow API. - - -

-struct Referent<T: store, key> has store
-
- - - -
-Fields - - -
-
- -id: address -
-
- -
-
- -value: option::Option<T> -
-
- -
-
- - -
- - - -## Struct `Borrow` - -A hot potato making sure the object is put back once borrowed. - - -

-struct Borrow
-
- - - -
-Fields - - -
-
- -ref: address -
-
- -
-
- -obj: object::ID -
-
- -
-
- - -
- - - -## Constants - - - - -The -Borrow does not match the -Referent. - - -

-const EWrongBorrow: u64 = 0;
-
- - - - - -An attempt to swap the -Referent.value with another object of the same type. - - -

-const EWrongValue: u64 = 1;
-
- - - - - -## Function `new` - -Create a new -Referent struct - - -

-public fun new<T: store, key>(value: T, ctx: &mut tx_context::TxContext): borrow::Referent<T>
-
- - - -
-Implementation - - -

-public fun new<T: key + store>(value: T, ctx: &mut TxContext): Referent<T> \{
-    Referent \{
-        id: tx_context::fresh_object_address(ctx),
-        value: option::some(value)
-    }
-}
-
- - - -
- - - -## Function `borrow` - -Borrow the -T from the -Referent receiving the -T and a -Borrow -hot potato. - - -

-public fun borrow<T: store, key>(self: &mut borrow::Referent<T>): (T, borrow::Borrow)
-
- - - -
-Implementation - - -

-public fun borrow<T: key + store>(self: &mut Referent<T>): (T, Borrow) \{
-    let value = self.value.extract();
-    let id = object::id(&value);
-
-    (value, Borrow \{
-        ref: self.id,
-        obj: id
-    })
-}
-
- - - -
- - - -## Function `put_back` - -Put an object and the -Borrow hot potato back. - - -

-public fun put_back<T: store, key>(self: &mut borrow::Referent<T>, value: T, borrow: borrow::Borrow)
-
- - - -
-Implementation - - -

-public fun put_back<T: key + store>(self: &mut Referent<T>, value: T, borrow: Borrow) \{
-    let Borrow \{ ref, obj } = borrow;
-
-    assert!(object::id(&value) == obj, EWrongValue);
-    assert!(self.id == ref, EWrongBorrow);
-    self.value.fill(value);
-}
-
- - - -
- - - -## Function `destroy` - -Unpack the -Referent struct and return the value. - - -

-public fun destroy<T: store, key>(self: borrow::Referent<T>): T
-
- - - -
-Implementation - - -

-public fun destroy<T: key + store>(self: Referent<T>): T \{
-    let Referent \{ id: _, value } = self;
-    value.destroy_some()
-}
-
- - - -
diff --git a/crates/iota-framework/docs/iota-framework/clock.mdx b/crates/iota-framework/docs/iota-framework/clock.mdx deleted file mode 100644 index c1c41727717..00000000000 --- a/crates/iota-framework/docs/iota-framework/clock.mdx +++ /dev/null @@ -1,189 +0,0 @@ ---- -title: Module `0x2::clock` ---- -import Link from '@docusaurus/Link'; - - -APIs for accessing time from move calls, via the -Clock: a unique -shared object that is created at 0x6 during genesis. - - -- [Resource `Clock`](#0x2_clock_Clock) -- [Constants](#@Constants_0) -- [Function `timestamp_ms`](#0x2_clock_timestamp_ms) -- [Function `create`](#0x2_clock_create) -- [Function `consensus_commit_prologue`](#0x2_clock_consensus_commit_prologue) - - -

-use 0x2::object;
-use 0x2::transfer;
-use 0x2::tx_context;
-
- - - - - -## Resource `Clock` - -Singleton shared object that exposes time to Move calls. This -object is found at address 0x6, and can only be read (accessed -via an immutable reference) by entry functions. - -Entry Functions that attempt to accept -Clock by mutable -reference or value will fail to verify, and honest validators -will not sign or execute transactions that use -Clock as an -input parameter, unless it is passed by immutable reference. - - -

-struct Clock has key
-
- - - -
-Fields - - -
-
- -id: object::UID -
-
- -
-
- -timestamp_ms: u64 -
-
- The clock's timestamp, which is set automatically by a - system transaction every time consensus commits a - schedule, or by -iota::clock::increment_for_testing during - testing. -
-
- - -
- - - -## Constants - - - - -Sender is not @0x0 the system address. - - -

-const ENotSystemAddress: u64 = 0;
-
- - - - - -## Function `timestamp_ms` - -The -clock's current timestamp as a running total of -milliseconds since an arbitrary point in the past. - - -

-public fun timestamp_ms(clock: &clock::Clock): u64
-
- - - -
-Implementation - - -

-public fun timestamp_ms(clock: &Clock): u64 \{
-    clock.timestamp_ms
-}
-
- - - -
- - - -## Function `create` - -Create and share the singleton Clock -- this function is -called exactly once, during genesis. - - -

-fun create(ctx: &tx_context::TxContext)
-
- - - -
-Implementation - - -

-fun create(ctx: &TxContext) \{
-    assert!(ctx.sender() == @0x0, ENotSystemAddress);
-
-    transfer::share_object(Clock \{
-        id: object::clock(),
-        // Initialised to zero, but set to a real timestamp by a
-        // system transaction before it can be witnessed by a move
-        // call.
-        timestamp_ms: 0,
-    })
-}
-
- - - -
- - - -## Function `consensus_commit_prologue` - - - -

-fun consensus_commit_prologue(clock: &mut clock::Clock, timestamp_ms: u64, ctx: &tx_context::TxContext)
-
- - - -
-Implementation - - -

-fun consensus_commit_prologue(
-    clock: &mut Clock,
-    timestamp_ms: u64,
-    ctx: &TxContext,
-) \{
-    // Validator will make a special system call with sender set as 0x0.
-    assert!(ctx.sender() == @0x0, ENotSystemAddress);
-
-    clock.timestamp_ms = timestamp_ms
-}
-
- - - -
diff --git a/crates/iota-framework/docs/iota-framework/coin.mdx b/crates/iota-framework/docs/iota-framework/coin.mdx deleted file mode 100644 index b1db888e786..00000000000 --- a/crates/iota-framework/docs/iota-framework/coin.mdx +++ /dev/null @@ -1,1508 +0,0 @@ ---- -title: Module `0x2::coin` ---- -import Link from '@docusaurus/Link'; - - -Defines the -Coin type - platform wide representation of fungible -tokens and coins. -Coin can be described as a secure wrapper around - -Balance type. - - -- [Resource `Coin`](#0x2_coin_Coin) -- [Resource `CoinMetadata`](#0x2_coin_CoinMetadata) -- [Resource `RegulatedCoinMetadata`](#0x2_coin_RegulatedCoinMetadata) -- [Resource `TreasuryCap`](#0x2_coin_TreasuryCap) -- [Resource `DenyCap`](#0x2_coin_DenyCap) -- [Struct `CurrencyCreated`](#0x2_coin_CurrencyCreated) -- [Constants](#@Constants_0) -- [Function `total_supply`](#0x2_coin_total_supply) -- [Function `treasury_into_supply`](#0x2_coin_treasury_into_supply) -- [Function `supply_immut`](#0x2_coin_supply_immut) -- [Function `supply_mut`](#0x2_coin_supply_mut) -- [Function `value`](#0x2_coin_value) -- [Function `balance`](#0x2_coin_balance) -- [Function `balance_mut`](#0x2_coin_balance_mut) -- [Function `from_balance`](#0x2_coin_from_balance) -- [Function `into_balance`](#0x2_coin_into_balance) -- [Function `take`](#0x2_coin_take) -- [Function `put`](#0x2_coin_put) -- [Function `join`](#0x2_coin_join) -- [Function `split`](#0x2_coin_split) -- [Function `divide_into_n`](#0x2_coin_divide_into_n) -- [Function `zero`](#0x2_coin_zero) -- [Function `destroy_zero`](#0x2_coin_destroy_zero) -- [Function `create_currency`](#0x2_coin_create_currency) -- [Function `create_regulated_currency`](#0x2_coin_create_regulated_currency) -- [Function `mint`](#0x2_coin_mint) -- [Function `mint_balance`](#0x2_coin_mint_balance) -- [Function `burn`](#0x2_coin_burn) -- [Function `deny_list_add`](#0x2_coin_deny_list_add) -- [Function `deny_list_remove`](#0x2_coin_deny_list_remove) -- [Function `deny_list_contains`](#0x2_coin_deny_list_contains) -- [Function `mint_and_transfer`](#0x2_coin_mint_and_transfer) -- [Function `update_name`](#0x2_coin_update_name) -- [Function `update_symbol`](#0x2_coin_update_symbol) -- [Function `update_description`](#0x2_coin_update_description) -- [Function `update_icon_url`](#0x2_coin_update_icon_url) -- [Function `get_decimals`](#0x2_coin_get_decimals) -- [Function `get_name`](#0x2_coin_get_name) -- [Function `get_symbol`](#0x2_coin_get_symbol) -- [Function `get_description`](#0x2_coin_get_description) -- [Function `get_icon_url`](#0x2_coin_get_icon_url) -- [Function `supply`](#0x2_coin_supply) - - -

-use 0x1::ascii;
-use 0x1::option;
-use 0x1::string;
-use 0x1::type_name;
-use 0x2::balance;
-use 0x2::deny_list;
-use 0x2::object;
-use 0x2::transfer;
-use 0x2::tx_context;
-use 0x2::types;
-use 0x2::url;
-
- - - - - -## Resource `Coin` - -A coin of type -T worth -value. Transferable and storable - - -

-struct Coin<T> has store, key
-
- - - -
-Fields - - -
-
- -id: object::UID -
-
- -
-
- -balance: balance::Balance<T> -
-
- -
-
- - -
- - - -## Resource `CoinMetadata` - -Each Coin type T created through -create_currency function will have a -unique instance of `CoinMetadata` that stores the metadata for this coin type. - - -

-struct CoinMetadata<T> has store, key
-
- - - -
-Fields - - -
-
- -id: object::UID -
-
- -
-
- -decimals: u8 -
-
- Number of decimal places the coin uses. - A coin with -value N and -decimals D should be shown as N / 10^D - E.g., a coin with -value 7002 and decimals 3 should be displayed as 7.002 - This is metadata for display usage only. -
-
- -name: string::String -
-
- Name for the token -
-
- -symbol: ascii::String -
-
- Symbol for the token -
-
- -description: string::String -
-
- Description of the token -
-
- -icon_url: option::Option<url::Url> -
-
- URL for the token logo -
-
- - -
- - - -## Resource `RegulatedCoinMetadata` - -Similar to CoinMetadata, but created only for regulated coins that use the DenyList. -This object is always immutable. - - -

-struct RegulatedCoinMetadata<T> has key
-
- - - -
-Fields - - -
-
- -id: object::UID -
-
- -
-
- -coin_metadata_object: object::ID -
-
- The ID of the coin's CoinMetadata object. -
-
- -deny_cap_object: object::ID -
-
- The ID of the coin's DenyCap object. -
-
- - -
- - - -## Resource `TreasuryCap` - -Capability allowing the bearer to mint and burn -coins of type -T. Transferable - - -

-struct TreasuryCap<T> has store, key
-
- - - -
-Fields - - -
-
- -id: object::UID -
-
- -
-
- -total_supply: balance::Supply<T> -
-
- -
-
- - -
- - - -## Resource `DenyCap` - -Capability allowing the bearer to freeze addresses, preventing those addresses from -interacting with the coin as an input to a transaction. - - -

-struct DenyCap<T> has store, key
-
- - - -
-Fields - - -
-
- -id: object::UID -
-
- -
-
- - -
- - - -## Struct `CurrencyCreated` - - - -

-struct CurrencyCreated<T> has copy, drop
-
- - - -
-Fields - - -
-
- -decimals: u8 -
-
- -
-
- - -
- - - -## Constants - - - - -Trying to split a coin more times than its balance allows. - - -

-const ENotEnough: u64 = 2;
-
- - - - - -The index into the deny list vector for the -iota::coin::Coin type. - - -

-const DENY_LIST_COIN_INDEX: u64 = 0;
-
- - - - - -A type passed to create_supply is not a one-time witness. - - -

-const EBadWitness: u64 = 0;
-
- - - - - -Invalid arguments are passed to a function. - - -

-const EInvalidArg: u64 = 1;
-
- - - - - -## Function `total_supply` - -Return the total number of -T's in circulation. - - -

-public fun total_supply<T>(cap: &coin::TreasuryCap<T>): u64
-
- - - -
-Implementation - - -

-public fun total_supply<T>(cap: &TreasuryCap<T>): u64 \{
-    balance::supply_value(&cap.total_supply)
-}
-
- - - -
- - - -## Function `treasury_into_supply` - -Unwrap -TreasuryCap getting the -Supply. - -Operation is irreversible. Supply cannot be converted into a -TreasuryCap due -to different security guarantees (TreasuryCap can be created only once for a type) - - -

-public fun treasury_into_supply<T>(treasury: coin::TreasuryCap<T>): balance::Supply<T>
-
- - - -
-Implementation - - -

-public fun treasury_into_supply<T>(treasury: TreasuryCap<T>): Supply<T> \{
-    let TreasuryCap \{ id, total_supply } = treasury;
-    id.delete();
-    total_supply
-}
-
- - - -
- - - -## Function `supply_immut` - -Get immutable reference to the treasury's -Supply. - - -

-public fun supply_immut<T>(treasury: &coin::TreasuryCap<T>): &balance::Supply<T>
-
- - - -
-Implementation - - -

-public fun supply_immut<T>(treasury: &TreasuryCap<T>): &Supply<T> \{
-    &treasury.total_supply
-}
-
- - - -
- - - -## Function `supply_mut` - -Get mutable reference to the treasury's -Supply. - - -

-public fun supply_mut<T>(treasury: &mut coin::TreasuryCap<T>): &mut balance::Supply<T>
-
- - - -
-Implementation - - -

-public fun supply_mut<T>(treasury: &mut TreasuryCap<T>): &mut Supply<T> \{
-    &mut treasury.total_supply
-}
-
- - - -
- - - -## Function `value` - -Public getter for the coin's value - - -

-public fun value<T>(self: &coin::Coin<T>): u64
-
- - - -
-Implementation - - -

-public fun value<T>(self: &Coin<T>): u64 \{
-    self.balance.value()
-}
-
- - - -
- - - -## Function `balance` - -Get immutable reference to the balance of a coin. - - -

-public fun balance<T>(coin: &coin::Coin<T>): &balance::Balance<T>
-
- - - -
-Implementation - - -

-public fun balance<T>(coin: &Coin<T>): &Balance<T> \{
-    &coin.balance
-}
-
- - - -
- - - -## Function `balance_mut` - -Get a mutable reference to the balance of a coin. - - -

-public fun balance_mut<T>(coin: &mut coin::Coin<T>): &mut balance::Balance<T>
-
- - - -
-Implementation - - -

-public fun balance_mut<T>(coin: &mut Coin<T>): &mut Balance<T> \{
-    &mut coin.balance
-}
-
- - - -
- - - -## Function `from_balance` - -Wrap a balance into a Coin to make it transferable. - - -

-public fun from_balance<T>(balance: balance::Balance<T>, ctx: &mut tx_context::TxContext): coin::Coin<T>
-
- - - -
-Implementation - - -

-public fun from_balance<T>(balance: Balance<T>, ctx: &mut TxContext): Coin<T> \{
-    Coin \{ id: object::new(ctx), balance }
-}
-
- - - -
- - - -## Function `into_balance` - -Destruct a Coin wrapper and keep the balance. - - -

-public fun into_balance<T>(coin: coin::Coin<T>): balance::Balance<T>
-
- - - -
-Implementation - - -

-public fun into_balance<T>(coin: Coin<T>): Balance<T> \{
-    let Coin \{ id, balance } = coin;
-    id.delete();
-    balance
-}
-
- - - -
- - - -## Function `take` - -Take a -Coin worth of -value from -Balance. -Aborts if -value > balance.value - - -

-public fun take<T>(balance: &mut balance::Balance<T>, value: u64, ctx: &mut tx_context::TxContext): coin::Coin<T>
-
- - - -
-Implementation - - -

-public fun take<T>(
-    balance: &mut Balance<T>, value: u64, ctx: &mut TxContext,
-): Coin<T> \{
-    Coin \{
-        id: object::new(ctx),
-        balance: balance.split(value)
-    }
-}
-
- - - -
- - - -## Function `put` - -Put a -Coin<T> to the -Balance<T>. - - -

-public fun put<T>(balance: &mut balance::Balance<T>, coin: coin::Coin<T>)
-
- - - -
-Implementation - - -

-public fun put<T>(balance: &mut Balance<T>, coin: Coin<T>) \{
-    balance.join(into_balance(coin));
-}
-
- - - -
- - - -## Function `join` - -Consume the coin -c and add its value to -self. -Aborts if -c.value + self.value > U64_MAX - - -

-public entry fun join<T>(self: &mut coin::Coin<T>, c: coin::Coin<T>)
-
- - - -
-Implementation - - -

-public entry fun join<T>(self: &mut Coin<T>, c: Coin<T>) \{
-    let Coin \{ id, balance } = c;
-    id.delete();
-    self.balance.join(balance);
-}
-
- - - -
- - - -## Function `split` - -Split coin -self to two coins, one with balance -split_amount, -and the remaining balance is left is -self. - - -

-public fun split<T>(self: &mut coin::Coin<T>, split_amount: u64, ctx: &mut tx_context::TxContext): coin::Coin<T>
-
- - - -
-Implementation - - -

-public fun split<T>(
-    self: &mut Coin<T>, split_amount: u64, ctx: &mut TxContext
-): Coin<T> \{
-    take(&mut self.balance, split_amount, ctx)
-}
-
- - - -
- - - -## Function `divide_into_n` - -Split coin -self into -n - 1 coins with equal balances. The remainder is left in - -self. Return newly created coins. - - -

-public fun divide_into_n<T>(self: &mut coin::Coin<T>, n: u64, ctx: &mut tx_context::TxContext): vector<coin::Coin<T>>
-
- - - -
-Implementation - - -

-public fun divide_into_n<T>(
-    self: &mut Coin<T>, n: u64, ctx: &mut TxContext
-): vector<Coin<T>> \{
-    assert!(n > 0, EInvalidArg);
-    assert!(n <= value(self), ENotEnough);
-
-    let mut vec = vector[];
-    let mut i = 0;
-    let split_amount = value(self) / n;
-    while (i < n - 1) \{
-        vec.push_back(self.split(split_amount, ctx));
-        i = i + 1;
-    };
-    vec
-}
-
- - - -
- - - -## Function `zero` - -Make any Coin with a zero value. Useful for placeholding -bids/payments or preemptively making empty balances. - - -

-public fun zero<T>(ctx: &mut tx_context::TxContext): coin::Coin<T>
-
- - - -
-Implementation - - -

-public fun zero<T>(ctx: &mut TxContext): Coin<T> \{
-    Coin \{ id: object::new(ctx), balance: balance::zero() }
-}
-
- - - -
- - - -## Function `destroy_zero` - -Destroy a coin with value zero - - -

-public fun destroy_zero<T>(c: coin::Coin<T>)
-
- - - -
-Implementation - - -

-public fun destroy_zero<T>(c: Coin<T>) \{
-    let Coin \{ id, balance } = c;
-    id.delete();
-    balance.destroy_zero()
-}
-
- - - -
- - - -## Function `create_currency` - -Create a new currency type -T as and return the -TreasuryCap for - -T to the caller. Can only be called with a -one-time-witness -type, ensuring that there's only one -TreasuryCap per -T. - - -

-public fun create_currency<T: drop>(witness: T, decimals: u8, symbol: vector<u8>, name: vector<u8>, description: vector<u8>, icon_url: option::Option<url::Url>, ctx: &mut tx_context::TxContext): (coin::TreasuryCap<T>, coin::CoinMetadata<T>)
-
- - - -
-Implementation - - -

-public fun create_currency<T: drop>(
-    witness: T,
-    decimals: u8,
-    symbol: vector<u8>,
-    name: vector<u8>,
-    description: vector<u8>,
-    icon_url: Option<Url>,
-    ctx: &mut TxContext
-): (TreasuryCap<T>, CoinMetadata<T>) \{
-    // Make sure there's only one instance of the type T
-    assert!(iota::types::is_one_time_witness(&witness), EBadWitness);
-
-    (
-        TreasuryCap \{
-            id: object::new(ctx),
-            total_supply: balance::create_supply(witness)
-        },
-        CoinMetadata \{
-            id: object::new(ctx),
-            decimals,
-            name: string::utf8(name),
-            symbol: ascii::string(symbol),
-            description: string::utf8(description),
-            icon_url
-        }
-    )
-}
-
- - - -
- - - -## Function `create_regulated_currency` - -This creates a new currency, via -create_currency, but with an extra capability that -allows for specific addresses to have their coins frozen. Those addresses cannot interact -with the coin as input objects. - - -

-public fun create_regulated_currency<T: drop>(witness: T, decimals: u8, symbol: vector<u8>, name: vector<u8>, description: vector<u8>, icon_url: option::Option<url::Url>, ctx: &mut tx_context::TxContext): (coin::TreasuryCap<T>, coin::DenyCap<T>, coin::CoinMetadata<T>)
-
- - - -
-Implementation - - -

-public fun create_regulated_currency<T: drop>(
-    witness: T,
-    decimals: u8,
-    symbol: vector<u8>,
-    name: vector<u8>,
-    description: vector<u8>,
-    icon_url: Option<Url>,
-    ctx: &mut TxContext
-): (TreasuryCap<T>, DenyCap<T>, CoinMetadata<T>) \{
-    let (treasury_cap, metadata) = create_currency(
-        witness,
-        decimals,
-        symbol,
-        name,
-        description,
-        icon_url,
-        ctx
-    );
-    let deny_cap = DenyCap \{
-        id: object::new(ctx),
-    };
-    transfer::freeze_object(RegulatedCoinMetadata<T> \{
-        id: object::new(ctx),
-        coin_metadata_object: object::id(&metadata),
-        deny_cap_object: object::id(&deny_cap),
-    });
-    (treasury_cap, deny_cap, metadata)
-}
-
- - - -
- - - -## Function `mint` - -Create a coin worth -value and increase the total supply -in -cap accordingly. - - -

-public fun mint<T>(cap: &mut coin::TreasuryCap<T>, value: u64, ctx: &mut tx_context::TxContext): coin::Coin<T>
-
- - - -
-Implementation - - -

-public fun mint<T>(
-    cap: &mut TreasuryCap<T>, value: u64, ctx: &mut TxContext,
-): Coin<T> \{
-    Coin \{
-        id: object::new(ctx),
-        balance: cap.total_supply.increase_supply(value)
-    }
-}
-
- - - -
- - - -## Function `mint_balance` - -Mint some amount of T as a -Balance and increase the total -supply in -cap accordingly. -Aborts if -value + -cap.total_supply >= U64_MAX - - -

-public fun mint_balance<T>(cap: &mut coin::TreasuryCap<T>, value: u64): balance::Balance<T>
-
- - - -
-Implementation - - -

-public fun mint_balance<T>(
-    cap: &mut TreasuryCap<T>, value: u64
-): Balance<T> \{
-    cap.total_supply.increase_supply(value)
-}
-
- - - -
- - - -## Function `burn` - -Destroy the coin -c and decrease the total supply in -cap -accordingly. - - -

-public entry fun burn<T>(cap: &mut coin::TreasuryCap<T>, c: coin::Coin<T>): u64
-
- - - -
-Implementation - - -

-public entry fun burn<T>(cap: &mut TreasuryCap<T>, c: Coin<T>): u64 \{
-    let Coin \{ id, balance } = c;
-    id.delete();
-    cap.total_supply.decrease_supply(balance)
-}
-
- - - -
- - - -## Function `deny_list_add` - -Adds the given address to the deny list, preventing it -from interacting with the specified coin type as an input to a transaction. - - -

-public fun deny_list_add<T>(deny_list: &mut deny_list::DenyList, _deny_cap: &mut coin::DenyCap<T>, addr: address, _ctx: &mut tx_context::TxContext)
-
- - - -
-Implementation - - -

-public fun deny_list_add<T>(
-   deny_list: &mut DenyList,
-   _deny_cap: &mut DenyCap<T>,
-   addr: address,
-   _ctx: &mut TxContext
-) \{
-    let `type` =
-        type_name::into_string(type_name::get_with_original_ids<T>()).into_bytes();
-    deny_list::add(
-        deny_list,
-        DENY_LIST_COIN_INDEX,
-        `type`,
-        addr,
-    )
-}
-
- - - -
- - - -## Function `deny_list_remove` - -Removes an address from the deny list. -Aborts with -ENotFrozen if the address is not already in the list. - - -

-public fun deny_list_remove<T>(deny_list: &mut deny_list::DenyList, _deny_cap: &mut coin::DenyCap<T>, addr: address, _ctx: &mut tx_context::TxContext)
-
- - - -
-Implementation - - -

-public fun deny_list_remove<T>(
-   deny_list: &mut DenyList,
-   _deny_cap: &mut DenyCap<T>,
-   addr: address,
-   _ctx: &mut TxContext
-) \{
-    let `type` =
-        type_name::into_string(type_name::get_with_original_ids<T>()).into_bytes();
-    deny_list::remove(
-        deny_list,
-        DENY_LIST_COIN_INDEX,
-        `type`,
-        addr,
-    )
-}
-
- - - -
- - - -## Function `deny_list_contains` - -Returns true iff the given address is denied for the given coin type. It will -return false if given a non-coin type. - - -

-public fun deny_list_contains<T>(freezer: &deny_list::DenyList, addr: address): bool
-
- - - -
-Implementation - - -

-public fun deny_list_contains<T>(
-   freezer: &DenyList,
-   addr: address,
-): bool \{
-    let name = type_name::get_with_original_ids<T>();
-    if (type_name::is_primitive(&name)) return false;
-
-    let `type` = type_name::into_string(name).into_bytes();
-    freezer.contains(DENY_LIST_COIN_INDEX, `type`, addr)
-}
-
- - - -
- - - -## Function `mint_and_transfer` - -Mint -amount of -Coin and send it to -recipient. Invokes -mint(). - - -

-public entry fun mint_and_transfer<T>(c: &mut coin::TreasuryCap<T>, amount: u64, recipient: address, ctx: &mut tx_context::TxContext)
-
- - - -
-Implementation - - -

-public entry fun mint_and_transfer<T>(
-    c: &mut TreasuryCap<T>, amount: u64, recipient: address, ctx: &mut TxContext
-) \{
-    transfer::public_transfer(mint(c, amount, ctx), recipient)
-}
-
- - - -
- - - -## Function `update_name` - -Update name of the coin in -CoinMetadata - - -

-public entry fun update_name<T>(_treasury: &coin::TreasuryCap<T>, metadata: &mut coin::CoinMetadata<T>, name: string::String)
-
- - - -
-Implementation - - -

-public entry fun update_name<T>(
-    _treasury: &TreasuryCap<T>, metadata: &mut CoinMetadata<T>, name: string::String
-) \{
-    metadata.name = name;
-}
-
- - - -
- - - -## Function `update_symbol` - -Update the symbol of the coin in -CoinMetadata - - -

-public entry fun update_symbol<T>(_treasury: &coin::TreasuryCap<T>, metadata: &mut coin::CoinMetadata<T>, symbol: ascii::String)
-
- - - -
-Implementation - - -

-public entry fun update_symbol<T>(
-    _treasury: &TreasuryCap<T>, metadata: &mut CoinMetadata<T>, symbol: ascii::String
-) \{
-    metadata.symbol = symbol;
-}
-
- - - -
- - - -## Function `update_description` - -Update the description of the coin in -CoinMetadata - - -

-public entry fun update_description<T>(_treasury: &coin::TreasuryCap<T>, metadata: &mut coin::CoinMetadata<T>, description: string::String)
-
- - - -
-Implementation - - -

-public entry fun update_description<T>(
-    _treasury: &TreasuryCap<T>, metadata: &mut CoinMetadata<T>, description: string::String
-) \{
-    metadata.description = description;
-}
-
- - - -
- - - -## Function `update_icon_url` - -Update the url of the coin in -CoinMetadata - - -

-public entry fun update_icon_url<T>(_treasury: &coin::TreasuryCap<T>, metadata: &mut coin::CoinMetadata<T>, url: ascii::String)
-
- - - -
-Implementation - - -

-public entry fun update_icon_url<T>(
-    _treasury: &TreasuryCap<T>, metadata: &mut CoinMetadata<T>, url: ascii::String
-) \{
-    metadata.icon_url = option::some(url::new_unsafe(url));
-}
-
- - - -
- - - -## Function `get_decimals` - - - -

-public fun get_decimals<T>(metadata: &coin::CoinMetadata<T>): u8
-
- - - -
-Implementation - - -

-public fun get_decimals<T>(metadata: &CoinMetadata<T>): u8 \{
-    metadata.decimals
-}
-
- - - -
- - - -## Function `get_name` - - - -

-public fun get_name<T>(metadata: &coin::CoinMetadata<T>): string::String
-
- - - -
-Implementation - - -

-public fun get_name<T>(metadata: &CoinMetadata<T>): string::String \{
-    metadata.name
-}
-
- - - -
- - - -## Function `get_symbol` - - - -

-public fun get_symbol<T>(metadata: &coin::CoinMetadata<T>): ascii::String
-
- - - -
-Implementation - - -

-public fun get_symbol<T>(metadata: &CoinMetadata<T>): ascii::String \{
-    metadata.symbol
-}
-
- - - -
- - - -## Function `get_description` - - - -

-public fun get_description<T>(metadata: &coin::CoinMetadata<T>): string::String
-
- - - -
-Implementation - - -

-public fun get_description<T>(metadata: &CoinMetadata<T>): string::String \{
-    metadata.description
-}
-
- - - -
- - - -## Function `get_icon_url` - - - -

-public fun get_icon_url<T>(metadata: &coin::CoinMetadata<T>): option::Option<url::Url>
-
- - - -
-Implementation - - -

-public fun get_icon_url<T>(metadata: &CoinMetadata<T>): Option<Url> \{
-    metadata.icon_url
-}
-
- - - -
- - - -## Function `supply` - - - -

-public fun supply<T>(treasury: &mut coin::TreasuryCap<T>): &balance::Supply<T>
-
- - - -
-Implementation - - -

-public fun supply<T>(treasury: &mut TreasuryCap<T>): &Supply<T> \{
-    &treasury.total_supply
-}
-
- - - -
diff --git a/crates/iota-framework/docs/iota-framework/coin_manager.mdx b/crates/iota-framework/docs/iota-framework/coin_manager.mdx deleted file mode 100644 index 7bdd2928a26..00000000000 --- a/crates/iota-framework/docs/iota-framework/coin_manager.mdx +++ /dev/null @@ -1,1493 +0,0 @@ ---- -title: Module `0x2::coin_manager` ---- -import Link from '@docusaurus/Link'; - - -The purpose of a CoinManager is to allow access to all -properties of a Coin on-chain from within a single shared object -This includes access to the total supply and metadata -In addition a optional maximum supply can be set and a custom -additional Metadata field can be added. - - -- [Resource `CoinManager`](#0x2_coin_manager_CoinManager) -- [Resource `CoinManagerTreasuryCap`](#0x2_coin_manager_CoinManagerTreasuryCap) -- [Resource `CoinManagerMetadataCap`](#0x2_coin_manager_CoinManagerMetadataCap) -- [Struct `ImmutableCoinMetadata`](#0x2_coin_manager_ImmutableCoinMetadata) -- [Struct `CoinManaged`](#0x2_coin_manager_CoinManaged) -- [Struct `TreasuryOwnershipRenounced`](#0x2_coin_manager_TreasuryOwnershipRenounced) -- [Struct `MetadataOwnershipRenounced`](#0x2_coin_manager_MetadataOwnershipRenounced) -- [Constants](#@Constants_0) -- [Function `new`](#0x2_coin_manager_new) -- [Function `new_with_immutable_metadata`](#0x2_coin_manager_new_with_immutable_metadata) -- [Function `create`](#0x2_coin_manager_create) -- [Function `add_additional_metadata`](#0x2_coin_manager_add_additional_metadata) -- [Function `replace_additional_metadata`](#0x2_coin_manager_replace_additional_metadata) -- [Function `additional_metadata`](#0x2_coin_manager_additional_metadata) -- [Function `enforce_maximum_supply`](#0x2_coin_manager_enforce_maximum_supply) -- [Function `renounce_treasury_ownership`](#0x2_coin_manager_renounce_treasury_ownership) -- [Function `renounce_metadata_ownership`](#0x2_coin_manager_renounce_metadata_ownership) -- [Function `supply_is_immutable`](#0x2_coin_manager_supply_is_immutable) -- [Function `metadata_is_immutable`](#0x2_coin_manager_metadata_is_immutable) -- [Function `metadata`](#0x2_coin_manager_metadata) -- [Function `immutable_metadata`](#0x2_coin_manager_immutable_metadata) -- [Function `total_supply`](#0x2_coin_manager_total_supply) -- [Function `maximum_supply`](#0x2_coin_manager_maximum_supply) -- [Function `available_supply`](#0x2_coin_manager_available_supply) -- [Function `has_maximum_supply`](#0x2_coin_manager_has_maximum_supply) -- [Function `supply_immut`](#0x2_coin_manager_supply_immut) -- [Function `mint`](#0x2_coin_manager_mint) -- [Function `mint_balance`](#0x2_coin_manager_mint_balance) -- [Function `burn`](#0x2_coin_manager_burn) -- [Function `mint_and_transfer`](#0x2_coin_manager_mint_and_transfer) -- [Function `update_name`](#0x2_coin_manager_update_name) -- [Function `update_symbol`](#0x2_coin_manager_update_symbol) -- [Function `update_description`](#0x2_coin_manager_update_description) -- [Function `update_icon_url`](#0x2_coin_manager_update_icon_url) -- [Function `decimals`](#0x2_coin_manager_decimals) -- [Function `name`](#0x2_coin_manager_name) -- [Function `symbol`](#0x2_coin_manager_symbol) -- [Function `description`](#0x2_coin_manager_description) -- [Function `icon_url`](#0x2_coin_manager_icon_url) - - -

-use 0x1::ascii;
-use 0x1::option;
-use 0x1::string;
-use 0x1::type_name;
-use 0x2::balance;
-use 0x2::coin;
-use 0x2::dynamic_field;
-use 0x2::event;
-use 0x2::object;
-use 0x2::tx_context;
-use 0x2::url;
-
- - - - - -## Resource `CoinManager` - -Holds all related objects to a Coin in a convenient shared function - - -

-struct CoinManager<T> has store, key
-
- - - -
-Fields - - -
-
- -id: object::UID -
-
- -
-
- -treasury_cap: coin::TreasuryCap<T> -
-
- The original TreasuryCap object as returned by -create_currency -
-
- -metadata: option::Option<coin::CoinMetadata<T>> -
-
- Metadata object, original one from the -coin module, if available -
-
- -immutable_metadata: option::Option<coin_manager::ImmutableCoinMetadata<T>> -
-
- Immutable Metadata object, only to be used as a last resort if the original metadata is frozen -
-
- -maximum_supply: option::Option<u64> -
-
- Optional maximum supply, if set you can't mint more as this number - can only be set once -
-
- -supply_immutable: bool -
-
- Flag indicating if the supply is considered immutable (TreasuryCap is exchanged for this) -
-
- -metadata_immutable: bool -
-
- Flag indicating if the metadata is considered immutable (MetadataCap is exchanged for this) -
-
- - -
- - - -## Resource `CoinManagerTreasuryCap` - -Like -TreasuryCap, but for dealing with -TreasuryCap inside -CoinManager objects - - -

-struct CoinManagerTreasuryCap<T> has store, key
-
- - - -
-Fields - - -
-
- -id: object::UID -
-
- -
-
- - -
- - - -## Resource `CoinManagerMetadataCap` - -Metadata has it's own Cap, independent of the -TreasuryCap - - -

-struct CoinManagerMetadataCap<T> has store, key
-
- - - -
-Fields - - -
-
- -id: object::UID -
-
- -
-
- - -
- - - -## Struct `ImmutableCoinMetadata` - -The immutable version of CoinMetadata, used in case of migrating from frozen objects -to a -CoinManager holding the metadata. - - -

-struct ImmutableCoinMetadata<T> has store
-
- - - -
-Fields - - -
-
- -decimals: u8 -
-
- Number of decimal places the coin uses. - A coin with -value N and -decimals D should be shown as N / 10^D - E.g., a coin with -value 7002 and decimals 3 should be displayed as 7.002 - This is metadata for display usage only. -
-
- -name: string::String -
-
- Name for the token -
-
- -symbol: ascii::String -
-
- Symbol for the token -
-
- -description: string::String -
-
- Description of the token -
-
- -icon_url: option::Option<url::Url> -
-
- URL for the token logo -
-
- - -
- - - -## Struct `CoinManaged` - -Event triggered once -Coin ownership is transfered to a new -CoinManager - - -

-struct CoinManaged has copy, drop
-
- - - -
-Fields - - -
-
- -coin_name: ascii::String -
-
- -
-
- - -
- - - -## Struct `TreasuryOwnershipRenounced` - -Event triggered if the ownership of the treasury part of a -CoinManager is renounced - - -

-struct TreasuryOwnershipRenounced has copy, drop
-
- - - -
-Fields - - -
-
- -coin_name: ascii::String -
-
- -
-
- - -
- - - -## Struct `MetadataOwnershipRenounced` - -Event triggered if the ownership of the metadata part of a -CoinManager is renounced - - -

-struct MetadataOwnershipRenounced has copy, drop
-
- - - -
-Fields - - -
-
- -coin_name: ascii::String -
-
- -
-
- - -
- - - -## Constants - - - - -The error returned if additional metadata already exists and you try to overwrite - - -

-const EAdditionalMetadataAlreadyExists: u64 = 2;
-
- - - - - -The error returned if you try to edit nonexisting additional metadata - - -

-const EAdditionalMetadataDoesNotExist: u64 = 3;
-
- - - - - -The error returned if a attempt is made to change the maximum supply after setting it - - -

-const EMaximumSupplyAlreadySet: u64 = 1;
-
- - - - - -The error returned when the maximum supply reached. - - -

-const EMaximumSupplyReached: u64 = 0;
-
- - - - - -The error returned if you try to edit immutable metadata - - -

-const ENoMutableMetadata: u64 = 4;
-
- - - - - -## Function `new` - -Wraps all important objects related to a -Coin inside a shared object - - -

-public fun new<T>(treasury_cap: coin::TreasuryCap<T>, metadata: coin::CoinMetadata<T>, ctx: &mut tx_context::TxContext): (coin_manager::CoinManagerTreasuryCap<T>, coin_manager::CoinManagerMetadataCap<T>, coin_manager::CoinManager<T>)
-
- - - -
-Implementation - - -

-public fun new<T> (
-    treasury_cap: TreasuryCap<T>,
-    metadata: CoinMetadata<T>,
-    ctx: &mut TxContext,
-): (CoinManagerTreasuryCap<T>, CoinManagerMetadataCap<T>, CoinManager<T>) \{
-
-    let manager = CoinManager \{
-        id: object::new(ctx),
-        treasury_cap,
-        metadata: option::some(metadata),
-        immutable_metadata: option::none(),
-        maximum_supply: option::none(),
-        supply_immutable: false,
-        metadata_immutable: false
-    };
-
-    event::emit(CoinManaged \{
-        coin_name: type_name::into_string(type_name::get<T>())
-    });
-
-    (
-        CoinManagerTreasuryCap<T> \{
-            id: object::new(ctx)
-        },
-        CoinManagerMetadataCap<T> \{
-            id: object::new(ctx)
-        },
-        manager
-    )
-}
-
- - - -
- - - -## Function `new_with_immutable_metadata` - -This function allows the same as -new but under the assumption the Metadata can not be transfered -This would typically be the case with -Coin instances where the metadata is already frozen. - - -

-public fun new_with_immutable_metadata<T>(treasury_cap: coin::TreasuryCap<T>, metadata: &coin::CoinMetadata<T>, ctx: &mut tx_context::TxContext): (coin_manager::CoinManagerTreasuryCap<T>, coin_manager::CoinManager<T>)
-
- - - -
-Implementation - - -

-public fun new_with_immutable_metadata<T> (
-    treasury_cap: TreasuryCap<T>,
-    metadata: &CoinMetadata<T>,
-    ctx: &mut TxContext,
-): (CoinManagerTreasuryCap<T>, CoinManager<T>) \{
-
-    let metacopy = ImmutableCoinMetadata<T> \{
-        decimals: metadata.get_decimals(),
-        name: metadata.get_name(),
-        symbol: metadata.get_symbol(),
-        description: metadata.get_description(),
-        icon_url: metadata.get_icon_url()
-    };
-
-    let manager = CoinManager \{
-        id: object::new(ctx),
-        treasury_cap,
-        metadata: option::none(),
-        immutable_metadata: option::some(metacopy),
-        maximum_supply: option::none(),
-        supply_immutable: false,
-        metadata_immutable: true
-    };
-
-    event::emit(CoinManaged \{
-        coin_name: type_name::into_string(type_name::get<T>())
-    });
-
-    (
-        CoinManagerTreasuryCap<T> \{
-            id: object::new(ctx)
-        },
-        manager
-    )
-}
-
- - - -
- - - -## Function `create` - -Convenience wrapper to create a new -Coin and instantly wrap the cap inside a -CoinManager - - -

-public fun create<T: drop>(witness: T, decimals: u8, symbol: vector<u8>, name: vector<u8>, description: vector<u8>, icon_url: option::Option<url::Url>, ctx: &mut tx_context::TxContext): (coin_manager::CoinManagerTreasuryCap<T>, coin_manager::CoinManagerMetadataCap<T>, coin_manager::CoinManager<T>)
-
- - - -
-Implementation - - -

-public fun create<T: drop> (
-    witness: T,
-    decimals: u8,
-    symbol: vector<u8>,
-    name: vector<u8>,
-    description: vector<u8>,
-    icon_url: Option<Url>,
-    ctx: &mut TxContext
-): (CoinManagerTreasuryCap<T>, CoinManagerMetadataCap<T>, CoinManager<T>) \{
-
-    let (cap, meta) = coin::create_currency(
-        witness,
-        decimals,
-        symbol,
-        name,
-        description,
-        icon_url,
-        ctx
-    );
-
-    new(cap, meta, ctx)
-}
-
- - - -
- - - -## Function `add_additional_metadata` - - - -

-public fun add_additional_metadata<T, Value: store>(_: &coin_manager::CoinManagerMetadataCap<T>, manager: &mut coin_manager::CoinManager<T>, value: Value)
-
- - - -
-Implementation - - -

-public fun add_additional_metadata<T, Value: store>(
-    _: &CoinManagerMetadataCap<T>,
-    manager: &mut CoinManager<T>,
-    value: Value
-) \{
-    assert!(!df::exists_(&manager.id, b"additional_metadata"), EAdditionalMetadataAlreadyExists);
-    df::add(&mut manager.id, b"additional_metadata", value);
-}
-
- - - -
- - - -## Function `replace_additional_metadata` - - - -

-public fun replace_additional_metadata<T, Value: store, OldValue: store>(_: &coin_manager::CoinManagerMetadataCap<T>, manager: &mut coin_manager::CoinManager<T>, value: Value): OldValue
-
- - - -
-Implementation - - -

-public fun replace_additional_metadata<T, Value: store, OldValue: store>(
-    _: &CoinManagerMetadataCap<T>,
-    manager: &mut CoinManager<T>,
-    value: Value
-): OldValue \{
-    assert!(df::exists_(&manager.id, b"additional_metadata"), EAdditionalMetadataDoesNotExist);
-    let old_value = df::remove<vector<u8>, OldValue>(&mut manager.id, b"additional_metadata");
-    df::add(&mut manager.id, b"additional_metadata", value);
-    old_value
-}
-
- - - -
- - - -## Function `additional_metadata` - - - -

-public fun additional_metadata<T, Value: store>(manager: &mut coin_manager::CoinManager<T>): &Value
-
- - - -
-Implementation - - -

-public fun additional_metadata<T, Value: store>(
-    manager: &mut CoinManager<T>
-): &Value \{
-    assert!(df::exists_(&manager.id, b"additional_metadata"), EAdditionalMetadataDoesNotExist);
-    let meta: &Value = df::borrow(&manager.id, b"additional_metadata");
-    meta
-}
-
- - - -
- - - -## Function `enforce_maximum_supply` - -A one-time callable function to set a maximum mintable supply on a coin. -This can only be set once and is irrevertable. - - -

-public fun enforce_maximum_supply<T>(_: &coin_manager::CoinManagerTreasuryCap<T>, manager: &mut coin_manager::CoinManager<T>, maximum_supply: u64)
-
- - - -
-Implementation - - -

-public fun enforce_maximum_supply<T>(
-    _: &CoinManagerTreasuryCap<T>,
-    manager: &mut CoinManager<T>,
-    maximum_supply: u64
-) \{
-    assert!(option::is_none(&manager.maximum_supply), EMaximumSupplyAlreadySet);
-    option::fill(&mut manager.maximum_supply, maximum_supply);
-}
-
- - - -
- - - -## Function `renounce_treasury_ownership` - -A irreversible action renouncing supply ownership which can be called if you hold the -CoinManagerTreasuryCap. -This action provides -Coin holders with some assurances if called, namely that there will -not be any new minting or changes to the supply from this point onward. The maximum supply -will be set to the current supply and will not be changed any more afterwards. - - -

-public fun renounce_treasury_ownership<T>(cap: coin_manager::CoinManagerTreasuryCap<T>, manager: &mut coin_manager::CoinManager<T>)
-
- - - -
-Implementation - - -

-public fun renounce_treasury_ownership<T>(
-    cap: CoinManagerTreasuryCap<T>,
-    manager: &mut CoinManager<T>
-) \{
-    // Deleting the Cap
-    let CoinManagerTreasuryCap \{ id } = cap;
-    object::delete(id);
-
-    // Updating the maximum supply to the total supply
-    let total_supply = total_supply(manager);
-    if(manager.has_maximum_supply()) \{
-        option::swap(&mut manager.maximum_supply, total_supply);
-    } else \{
-        option::fill(&mut manager.maximum_supply, total_supply);
-    };
-
-    // Setting ownership renounced to true
-    manager.supply_immutable = true;
-
-    event::emit(TreasuryOwnershipRenounced \{
-        coin_name: type_name::into_string(type_name::get<T>())
-    });
-}
-
- - - -
- - - -## Function `renounce_metadata_ownership` - -A irreversible action renouncing manager ownership which can be called if you hold the -CoinManagerMetadataCap. -This action provides -Coin holders with some assurances if called, namely that there will -not be any changes to the metadata from this point onward. - - -

-public fun renounce_metadata_ownership<T>(cap: coin_manager::CoinManagerMetadataCap<T>, manager: &mut coin_manager::CoinManager<T>)
-
- - - -
-Implementation - - -

-public fun renounce_metadata_ownership<T>(
-    cap: CoinManagerMetadataCap<T>,
-    manager: &mut CoinManager<T>
-) \{
-    // Deleting the Cap
-    let CoinManagerMetadataCap \{ id } = cap;
-    object::delete(id);
-
-    // Setting ownership renounced to true
-    manager.metadata_immutable = true;
-
-    event::emit(MetadataOwnershipRenounced \{
-        coin_name: type_name::into_string(type_name::get<T>())
-    });
-}
-
- - - -
- - - -## Function `supply_is_immutable` - -Convenience function allowing users to query if the ownership of the supply of this -Coin -and thus the ability to mint new -Coin has been renounced. - - -

-public fun supply_is_immutable<T>(manager: &coin_manager::CoinManager<T>): bool
-
- - - -
-Implementation - - -

-public fun supply_is_immutable<T>(manager: &CoinManager<T>): bool \{
-    manager.supply_immutable
-}
-
- - - -
- - - -## Function `metadata_is_immutable` - -Convenience function allowing users to query if the ownership of the metadata management -and thus the ability to change any of the metadata has been renounced. - - -

-public fun metadata_is_immutable<T>(manager: &coin_manager::CoinManager<T>): bool
-
- - - -
-Implementation - - -

-public fun metadata_is_immutable<T>(manager: &CoinManager<T>): bool \{
-    manager.metadata_immutable || option::is_some(&manager.immutable_metadata)
-}
-
- - - -
- - - -## Function `metadata` - - - -

-public fun metadata<T>(manager: &coin_manager::CoinManager<T>): &coin::CoinMetadata<T>
-
- - - -
-Implementation - - -

-public fun metadata<T>(manager: &CoinManager<T>): &CoinMetadata<T> \{
-    option::borrow(&manager.metadata)
-}
-
- - - -
- - - -## Function `immutable_metadata` - - - -

-public fun immutable_metadata<T>(manager: &coin_manager::CoinManager<T>): &coin_manager::ImmutableCoinMetadata<T>
-
- - - -
-Implementation - - -

-public fun immutable_metadata<T>(manager: &CoinManager<T>): &ImmutableCoinMetadata<T> \{
-    option::borrow(&manager.immutable_metadata)
-}
-
- - - -
- - - -## Function `total_supply` - -Get the total supply as a number - - -

-public fun total_supply<T>(manager: &coin_manager::CoinManager<T>): u64
-
- - - -
-Implementation - - -

-public fun total_supply<T>(manager: &CoinManager<T>): u64 \{
-    coin::total_supply(&manager.treasury_cap)
-}
-
- - - -
- - - -## Function `maximum_supply` - -Get the maximum supply possible as a number. -If no maximum set it's the maximum u64 possible - - -

-public fun maximum_supply<T>(manager: &coin_manager::CoinManager<T>): u64
-
- - - -
-Implementation - - -

-public fun maximum_supply<T>(manager: &CoinManager<T>): u64 \{
-    option::get_with_default(&manager.maximum_supply, 18_446_744_073_709_551_615u64)
-}
-
- - - -
- - - -## Function `available_supply` - -Convenience function returning the remaining supply that can be minted still - - -

-public fun available_supply<T>(manager: &coin_manager::CoinManager<T>): u64
-
- - - -
-Implementation - - -

-public fun available_supply<T>(manager: &CoinManager<T>): u64 \{
-    maximum_supply(manager) - total_supply(manager)
-}
-
- - - -
- - - -## Function `has_maximum_supply` - -Returns if a maximum supply has been set for this Coin or not - - -

-public fun has_maximum_supply<T>(manager: &coin_manager::CoinManager<T>): bool
-
- - - -
-Implementation - - -

-public fun has_maximum_supply<T>(manager: &CoinManager<T>): bool \{
-    option::is_some(&manager.maximum_supply)
-}
-
- - - -
- - - -## Function `supply_immut` - -Get immutable reference to the treasury's -Supply. - - -

-public fun supply_immut<T>(manager: &coin_manager::CoinManager<T>): &balance::Supply<T>
-
- - - -
-Implementation - - -

-public fun supply_immut<T>(manager: &CoinManager<T>): &Supply<T> \{
-    coin::supply_immut(&manager.treasury_cap)
-}
-
- - - -
- - - -## Function `mint` - -Create a coin worth -value and increase the total supply -in -cap accordingly. - - -

-public fun mint<T>(_: &coin_manager::CoinManagerTreasuryCap<T>, manager: &mut coin_manager::CoinManager<T>, value: u64, ctx: &mut tx_context::TxContext): coin::Coin<T>
-
- - - -
-Implementation - - -

-public fun mint<T>(
-    _: &CoinManagerTreasuryCap<T>,
-    manager: &mut CoinManager<T>,
-    value: u64,
-    ctx: &mut TxContext
-): Coin<T> \{
-    assert!(total_supply(manager) + value <= maximum_supply(manager), EMaximumSupplyReached);
-    coin::mint(&mut manager.treasury_cap, value, ctx)
-}
-
- - - -
- - - -## Function `mint_balance` - -Mint some amount of T as a -Balance and increase the total -supply in -cap accordingly. -Aborts if -value + -cap.total_supply >= U64_MAX - - -

-public fun mint_balance<T>(_: &coin_manager::CoinManagerTreasuryCap<T>, manager: &mut coin_manager::CoinManager<T>, value: u64): balance::Balance<T>
-
- - - -
-Implementation - - -

-public fun mint_balance<T>(
-    _: &CoinManagerTreasuryCap<T>,
-    manager: &mut CoinManager<T>,
-    value: u64
-): Balance<T> \{
-    assert!(total_supply(manager) + value <= maximum_supply(manager), EMaximumSupplyReached);
-    coin::mint_balance(&mut manager.treasury_cap, value)
-}
-
- - - -
- - - -## Function `burn` - -Destroy the coin -c and decrease the total supply in -cap -accordingly. - - -

-public entry fun burn<T>(_: &coin_manager::CoinManagerTreasuryCap<T>, manager: &mut coin_manager::CoinManager<T>, c: coin::Coin<T>): u64
-
- - - -
-Implementation - - -

-public entry fun burn<T>(
-    _: &CoinManagerTreasuryCap<T>,
-    manager: &mut CoinManager<T>,
-    c: Coin<T>
-): u64 \{
-    coin::burn(&mut manager.treasury_cap, c)
-}
-
- - - -
- - - -## Function `mint_and_transfer` - -Mint -amount of -Coin and send it to -recipient. Invokes -mint(). - - -

-public fun mint_and_transfer<T>(_: &coin_manager::CoinManagerTreasuryCap<T>, manager: &mut coin_manager::CoinManager<T>, amount: u64, recipient: address, ctx: &mut tx_context::TxContext)
-
- - - -
-Implementation - - -

-public fun mint_and_transfer<T>(
-   _: &CoinManagerTreasuryCap<T>,
-   manager: &mut CoinManager<T>,
-   amount: u64,
-   recipient: address,
-   ctx: &mut TxContext
-) \{
-    assert!(total_supply(manager) + amount <= maximum_supply(manager), EMaximumSupplyReached);
-    coin::mint_and_transfer(&mut manager.treasury_cap, amount, recipient, ctx)
-}
-
- - - -
- - - -## Function `update_name` - -Update the -name of the coin in the -CoinMetadata. - - -

-public fun update_name<T>(_: &coin_manager::CoinManagerMetadataCap<T>, manager: &mut coin_manager::CoinManager<T>, name: string::String)
-
- - - -
-Implementation - - -

-public fun update_name<T>(
-    _: &CoinManagerMetadataCap<T>,
-    manager: &mut CoinManager<T>,
-    name: string::String
-) \{
-    assert!(manager.metadata_is_immutable(), ENoMutableMetadata);
-    coin::update_name(&manager.treasury_cap, option::borrow_mut(&mut manager.metadata), name)
-}
-
- - - -
- - - -## Function `update_symbol` - -Update the -symbol of the coin in the -CoinMetadata. - - -

-public fun update_symbol<T>(_: &coin_manager::CoinManagerMetadataCap<T>, manager: &mut coin_manager::CoinManager<T>, symbol: ascii::String)
-
- - - -
-Implementation - - -

-public fun update_symbol<T>(
-    _: &CoinManagerMetadataCap<T>,
-    manager: &mut CoinManager<T>,
-    symbol: ascii::String
-) \{
-    assert!(manager.metadata_is_immutable(), ENoMutableMetadata);
-    coin::update_symbol(&manager.treasury_cap, option::borrow_mut(&mut manager.metadata), symbol)
-}
-
- - - -
- - - -## Function `update_description` - -Update the -description of the coin in the -CoinMetadata. - - -

-public fun update_description<T>(_: &coin_manager::CoinManagerMetadataCap<T>, manager: &mut coin_manager::CoinManager<T>, description: string::String)
-
- - - -
-Implementation - - -

-public fun update_description<T>(
-    _: &CoinManagerMetadataCap<T>,
-    manager: &mut CoinManager<T>,
-    description: string::String
-) \{
-    assert!(manager.metadata_is_immutable(), ENoMutableMetadata);
-    coin::update_description(&manager.treasury_cap, option::borrow_mut(&mut manager.metadata), description)
-}
-
- - - -
- - - -## Function `update_icon_url` - -Update the -url of the coin in the -CoinMetadata - - -

-public fun update_icon_url<T>(_: &coin_manager::CoinManagerMetadataCap<T>, manager: &mut coin_manager::CoinManager<T>, url: ascii::String)
-
- - - -
-Implementation - - -

-public fun update_icon_url<T>(
-    _: &CoinManagerMetadataCap<T>,
-    manager: &mut CoinManager<T>,
-    url: ascii::String
-) \{
-    assert!(manager.metadata_is_immutable(), ENoMutableMetadata);
-    coin::update_icon_url(&manager.treasury_cap, option::borrow_mut(&mut manager.metadata), url)
-}
-
- - - -
- - - -## Function `decimals` - - - -

-public fun decimals<T>(manager: &coin_manager::CoinManager<T>): u8
-
- - - -
-Implementation - - -

-public fun decimals<T>(manager: &CoinManager<T>): u8 \{
-    if(option::is_some(&manager.metadata)) \{
-        coin::get_decimals(option::borrow(&manager.metadata))
-    } else \{
-        option::borrow(&manager.immutable_metadata).decimals
-    }
-}
-
- - - -
- - - -## Function `name` - - - -

-public fun name<T>(manager: &coin_manager::CoinManager<T>): string::String
-
- - - -
-Implementation - - -

-public fun name<T>(manager: &CoinManager<T>): string::String \{
-    if(option::is_some(&manager.metadata)) \{
-        coin::get_name(option::borrow(&manager.metadata))
-    } else \{
-        option::borrow(&manager.immutable_metadata).name
-    }
-}
-
- - - -
- - - -## Function `symbol` - - - -

-public fun symbol<T>(manager: &coin_manager::CoinManager<T>): ascii::String
-
- - - -
-Implementation - - -

-public fun symbol<T>(manager: &CoinManager<T>): ascii::String \{
-    if(option::is_some(&manager.metadata)) \{
-        coin::get_symbol(option::borrow(&manager.metadata))
-    } else \{
-        option::borrow(&manager.immutable_metadata).symbol
-    }
-}
-
- - - -
- - - -## Function `description` - - - -

-public fun description<T>(manager: &coin_manager::CoinManager<T>): string::String
-
- - - -
-Implementation - - -

-public fun description<T>(manager: &CoinManager<T>): string::String \{
-    if(option::is_some(&manager.metadata)) \{
-        coin::get_description(option::borrow(&manager.metadata))
-    } else \{
-        option::borrow(&manager.immutable_metadata).description
-    }
-}
-
- - - -
- - - -## Function `icon_url` - - - -

-public fun icon_url<T>(manager: &coin_manager::CoinManager<T>): option::Option<url::Url>
-
- - - -
-Implementation - - -

-public fun icon_url<T>(manager: &CoinManager<T>): Option<Url> \{
-    if(option::is_some(&manager.metadata)) \{
-        coin::get_icon_url(option::borrow(&manager.metadata))
-    } else \{
-        option::borrow(&manager.immutable_metadata).icon_url
-    }
-}
-
- - - -
diff --git a/crates/iota-framework/docs/iota-framework/deny_list.mdx b/crates/iota-framework/docs/iota-framework/deny_list.mdx deleted file mode 100644 index 60d7049eaa0..00000000000 --- a/crates/iota-framework/docs/iota-framework/deny_list.mdx +++ /dev/null @@ -1,445 +0,0 @@ ---- -title: Module `0x2::deny_list` ---- -import Link from '@docusaurus/Link'; - - -Defines the -DenyList type. The -DenyList shared object is used to restrict access to -instances of certain core types from being used as inputs by specified addresses in the deny -list. - - -- [Resource `DenyList`](#0x2_deny_list_DenyList) -- [Resource `PerTypeList`](#0x2_deny_list_PerTypeList) -- [Constants](#@Constants_0) -- [Function `add`](#0x2_deny_list_add) -- [Function `per_type_list_add`](#0x2_deny_list_per_type_list_add) -- [Function `remove`](#0x2_deny_list_remove) -- [Function `per_type_list_remove`](#0x2_deny_list_per_type_list_remove) -- [Function `contains`](#0x2_deny_list_contains) -- [Function `per_type_list_contains`](#0x2_deny_list_per_type_list_contains) -- [Function `create`](#0x2_deny_list_create) -- [Function `per_type_list`](#0x2_deny_list_per_type_list) - - -

-use 0x2::bag;
-use 0x2::object;
-use 0x2::table;
-use 0x2::transfer;
-use 0x2::tx_context;
-use 0x2::vec_set;
-
- - - - - -## Resource `DenyList` - -A shared object that stores the addresses that are blocked for a given core type. - - -

-struct DenyList has key
-
- - - -
-Fields - - -
-
- -id: object::UID -
-
- -
-
- -lists: bag::Bag -
-
- The individual deny lists. -
-
- - -
- - - -## Resource `PerTypeList` - -Stores the addresses that are denied for a given core type. - - -

-struct PerTypeList has store, key
-
- - - -
-Fields - - -
-
- -id: object::UID -
-
- -
-
- -denied_count: table::Table<address, u64> -
-
- Number of object types that have been banned for a given address. - Used to quickly skip checks for most addresses. -
-
- -denied_addresses: table::Table<vector<u8>, vec_set::VecSet<address>> -
-
- Set of addresses that are banned for a given type. - For example with -iota::coin::Coin: If addresses A and B are banned from using - "0...0123::my_coin::MY_COIN", this will be "0...0123::my_coin::MY_COIN" -> \{A, B}. -
-
- - -
- - - -## Constants - - - - -Trying to create a deny list object when not called by the system address. - - -

-const ENotSystemAddress: u64 = 0;
-
- - - - - -The index into the deny list vector for the -iota::coin::Coin type. - - -

-const COIN_INDEX: u64 = 0;
-
- - - - - -The specified address to be removed is not already in the deny list. - - -

-const ENotDenied: u64 = 1;
-
- - - - - -## Function `add` - -Adds the given address to the deny list of the specified type, preventing it -from interacting with instances of that type as an input to a transaction. For coins, -the type specified is the type of the coin, not the coin type itself. For example, -"00...0123::my_coin::MY_COIN" would be the type, not "00...02::coin::Coin". - - -

-public(friend) fun add(deny_list: &mut deny_list::DenyList, per_type_index: u64, type: vector<u8>, addr: address)
-
- - - -
-Implementation - - -

-public(package) fun add(
-    deny_list: &mut DenyList,
-    per_type_index: u64,
-    `type`: vector<u8>,
-    addr: address,
-) \{
-    let bag_entry: &mut PerTypeList = &mut deny_list.lists[per_type_index];
-    bag_entry.per_type_list_add(`type`, addr)
-}
-
- - - -
- - - -## Function `per_type_list_add` - - - -

-fun per_type_list_add(list: &mut deny_list::PerTypeList, type: vector<u8>, addr: address)
-
- - - -
-Implementation - - -

-fun per_type_list_add(
-    list: &mut PerTypeList,
-    `type`: vector<u8>,
-    addr: address,
-) \{
-    if (!list.denied_addresses.contains(`type`)) \{
-        list.denied_addresses.add(`type`, vec_set::empty());
-    };
-    let denied_addresses = &mut list.denied_addresses[`type`];
-    let already_denied = denied_addresses.contains(&addr);
-    if (already_denied) return;
-
-    denied_addresses.insert(addr);
-    if (!list.denied_count.contains(addr)) \{
-        list.denied_count.add(addr, 0);
-    };
-    let denied_count = &mut list.denied_count[addr];
-    *denied_count = *denied_count + 1;
-}
-
- - - -
- - - -## Function `remove` - -Removes a previously denied address from the list. -Aborts with -ENotDenied if the address is not on the list. - - -

-public(friend) fun remove(deny_list: &mut deny_list::DenyList, per_type_index: u64, type: vector<u8>, addr: address)
-
- - - -
-Implementation - - -

-public(package) fun remove(
-    deny_list: &mut DenyList,
-    per_type_index: u64,
-    `type`: vector<u8>,
-    addr: address,
-) \{
-    per_type_list_remove(&mut deny_list.lists[per_type_index], `type`, addr)
-}
-
- - - -
- - - -## Function `per_type_list_remove` - - - -

-fun per_type_list_remove(list: &mut deny_list::PerTypeList, type: vector<u8>, addr: address)
-
- - - -
-Implementation - - -

-fun per_type_list_remove(
-    list: &mut PerTypeList,
-    `type`: vector<u8>,
-    addr: address,
-) \{
-    let denied_addresses = &mut list.denied_addresses[`type`];
-    assert!(denied_addresses.contains(&addr), ENotDenied);
-    denied_addresses.remove(&addr);
-    let denied_count = &mut list.denied_count[addr];
-    *denied_count = *denied_count - 1;
-    if (*denied_count == 0) \{
-        list.denied_count.remove(addr);
-    }
-}
-
- - - -
- - - -## Function `contains` - -Returns true iff the given address is denied for the given type. - - -

-public(friend) fun contains(deny_list: &deny_list::DenyList, per_type_index: u64, type: vector<u8>, addr: address): bool
-
- - - -
-Implementation - - -

-public(package) fun contains(
-    deny_list: &DenyList,
-    per_type_index: u64,
-    `type`: vector<u8>,
-    addr: address,
-): bool \{
-    per_type_list_contains(&deny_list.lists[per_type_index], `type`, addr)
-}
-
- - - -
- - - -## Function `per_type_list_contains` - - - -

-fun per_type_list_contains(list: &deny_list::PerTypeList, type: vector<u8>, addr: address): bool
-
- - - -
-Implementation - - -

-fun per_type_list_contains(
-    list: &PerTypeList,
-    `type`: vector<u8>,
-    addr: address,
-): bool \{
-    if (!list.denied_count.contains(addr)) return false;
-
-    let denied_count = &list.denied_count[addr];
-    if (*denied_count == 0) return false;
-
-    if (!list.denied_addresses.contains(`type`)) return false;
-
-    let denied_addresses = &list.denied_addresses[`type`];
-    denied_addresses.contains(&addr)
-}
-
- - - -
- - - -## Function `create` - -Creation of the deny list object is restricted to the system address -via a system transaction. - - -

-fun create(ctx: &mut tx_context::TxContext)
-
- - - -
-Implementation - - -

-fun create(ctx: &mut TxContext) \{
-    assert!(ctx.sender() == @0x0, ENotSystemAddress);
-
-    let mut lists = bag::new(ctx);
-    lists.add(COIN_INDEX, per_type_list(ctx));
-    let deny_list_object = DenyList \{
-        id: object::iota_deny_list_object_id(),
-        lists,
-    };
-    transfer::share_object(deny_list_object);
-}
-
- - - -
- - - -## Function `per_type_list` - - - -

-fun per_type_list(ctx: &mut tx_context::TxContext): deny_list::PerTypeList
-
- - - -
-Implementation - - -

-fun per_type_list(ctx: &mut TxContext): PerTypeList \{
-    PerTypeList \{
-        id: object::new(ctx),
-        denied_count: table::new(ctx),
-        denied_addresses: table::new(ctx),
-    }
-}
-
- - - -
diff --git a/crates/iota-framework/docs/iota-framework/display.mdx b/crates/iota-framework/docs/iota-framework/display.mdx deleted file mode 100644 index 97021ff7bcf..00000000000 --- a/crates/iota-framework/docs/iota-framework/display.mdx +++ /dev/null @@ -1,622 +0,0 @@ ---- -title: Module `0x2::display` ---- -import Link from '@docusaurus/Link'; - - -Defines a Display struct which defines the way an Object -should be displayed. The intention is to keep data as independent -from its display as possible, protecting the development process -and keeping it separate from the ecosystem agreements. - -Each of the fields of the Display object should allow for pattern -substitution and filling-in the pieces using the data from the object T. - -More entry functions might be added in the future depending on the use cases. - - -- [Resource `Display`](#0x2_display_Display) -- [Struct `DisplayCreated`](#0x2_display_DisplayCreated) -- [Struct `VersionUpdated`](#0x2_display_VersionUpdated) -- [Constants](#@Constants_0) -- [Function `new`](#0x2_display_new) -- [Function `new_with_fields`](#0x2_display_new_with_fields) -- [Function `create_and_keep`](#0x2_display_create_and_keep) -- [Function `update_version`](#0x2_display_update_version) -- [Function `add`](#0x2_display_add) -- [Function `add_multiple`](#0x2_display_add_multiple) -- [Function `edit`](#0x2_display_edit) -- [Function `remove`](#0x2_display_remove) -- [Function `is_authorized`](#0x2_display_is_authorized) -- [Function `version`](#0x2_display_version) -- [Function `fields`](#0x2_display_fields) -- [Function `create_internal`](#0x2_display_create_internal) -- [Function `add_internal`](#0x2_display_add_internal) - - -

-use 0x1::string;
-use 0x2::event;
-use 0x2::object;
-use 0x2::package;
-use 0x2::transfer;
-use 0x2::tx_context;
-use 0x2::vec_map;
-
- - - - - -## Resource `Display` - -The `Display` object. Defines the way a T instance should be -displayed. Display object can only be created and modified with -a PublisherCap, making sure that the rules are set by the owner -of the type. - -Each of the display properties should support patterns outside -of the system, making it simpler to customize Display based -on the property values of an Object. -``` -// Example of a display object -Display<0x...::capy::Capy> { -fields: - - - - -} -``` - -Uses only String type due to external-facing nature of the object, -the property names have a priority over their types. - - -

-struct Display<T: key> has store, key
-
- - - -
-Fields - - -
-
- -id: object::UID -
-
- -
-
- -fields: vec_map::VecMap<string::String, string::String> -
-
- Contains fields for display. Currently supported - fields are: name, link, image and description. -
-
- -version: u16 -
-
- Version that can only be updated manually by the Publisher. -
-
- - -
- - - -## Struct `DisplayCreated` - -Event: emitted when a new Display object has been created for type T. -Type signature of the event corresponds to the type while id serves for -the discovery. - -Since Iota RPC supports querying events by type, finding a Display for the T -would be as simple as looking for the first event with -Display<T>. - - -

-struct DisplayCreated<T: key> has copy, drop
-
- - - -
-Fields - - -
-
- -id: object::ID -
-
- -
-
- - -
- - - -## Struct `VersionUpdated` - -Version of Display got updated - - - -

-struct VersionUpdated<T: key> has copy, drop
-
- - - -
-Fields - - -
-
- -id: object::ID -
-
- -
-
- -version: u16 -
-
- -
-
- -fields: vec_map::VecMap<string::String, string::String> -
-
- -
-
- - -
- - - -## Constants - - - - -For when T does not belong to the package -Publisher. - - -

-const ENotOwner: u64 = 0;
-
- - - - - -For when vectors passed into one of the multiple insert functions -don't match in their lengths. - - -

-const EVecLengthMismatch: u64 = 1;
-
- - - - - -## Function `new` - -Create an empty Display object. It can either be shared empty or filled -with data right away via cheaper -set_owned method. - - -

-public fun new<T: key>(pub: &package::Publisher, ctx: &mut tx_context::TxContext): display::Display<T>
-
- - - -
-Implementation - - -

-public fun new<T: key>(pub: &Publisher, ctx: &mut TxContext): Display<T> \{
-    assert!(is_authorized<T>(pub), ENotOwner);
-    create_internal(ctx)
-}
-
- - - -
- - - -## Function `new_with_fields` - -Create a new `Display` object with a set of fields. - - -

-public fun new_with_fields<T: key>(pub: &package::Publisher, fields: vector<string::String>, values: vector<string::String>, ctx: &mut tx_context::TxContext): display::Display<T>
-
- - - -
-Implementation - - -

-public fun new_with_fields<T: key>(
-    pub: &Publisher, fields: vector<String>, values: vector<String>, ctx: &mut TxContext
-): Display<T> \{
-    let len = fields.length();
-    assert!(len == values.length(), EVecLengthMismatch);
-
-    let mut i = 0;
-    let mut display = new<T>(pub, ctx);
-    while (i < len) \{
-        display.add_internal(fields[i], values[i]);
-        i = i + 1;
-    };
-
-    display
-}
-
- - - -
- - - -## Function `create_and_keep` - -Create a new empty `Display` object and keep it. - - -

-public entry fun create_and_keep<T: key>(pub: &package::Publisher, ctx: &mut tx_context::TxContext)
-
- - - -
-Implementation - - -

-entry public fun create_and_keep<T: key>(pub: &Publisher, ctx: &mut TxContext) \{
-    transfer::public_transfer(new<T>(pub, ctx), ctx.sender())
-}
-
- - - -
- - - -## Function `update_version` - -Manually bump the version and emit an event with the updated version's contents. - - -

-public entry fun update_version<T: key>(display: &mut display::Display<T>)
-
- - - -
-Implementation - - -

-entry public fun update_version<T: key>(
-    display: &mut Display<T>
-) \{
-    display.version = display.version + 1;
-    event::emit(VersionUpdated<T> \{
-        version: display.version,
-        fields: *&display.fields,
-        id: display.id.to_inner(),
-    })
-}
-
- - - -
- - - -## Function `add` - -Sets a custom -name field with the -value. - - -

-public entry fun add<T: key>(self: &mut display::Display<T>, name: string::String, value: string::String)
-
- - - -
-Implementation - - -

-entry public fun add<T: key>(self: &mut Display<T>, name: String, value: String) \{
-    self.add_internal(name, value)
-}
-
- - - -
- - - -## Function `add_multiple` - -Sets multiple -fields with -values. - - -

-public entry fun add_multiple<T: key>(self: &mut display::Display<T>, fields: vector<string::String>, values: vector<string::String>)
-
- - - -
-Implementation - - -

-entry public fun add_multiple<T: key>(
-    self: &mut Display<T>, fields: vector<String>, values: vector<String>
-) \{
-    let len = fields.length();
-    assert!(len == values.length(), EVecLengthMismatch);
-
-    let mut i = 0;
-    while (i < len) \{
-        self.add_internal(fields[i], values[i]);
-        i = i + 1;
-    };
-}
-
- - - -
- - - -## Function `edit` - -Change the value of the field. -TODO (long run): version changes; - - -

-public entry fun edit<T: key>(self: &mut display::Display<T>, name: string::String, value: string::String)
-
- - - -
-Implementation - - -

-entry public fun edit<T: key>(self: &mut Display<T>, name: String, value: String) \{
-    let (_, _) = self.fields.remove(&name);
-    self.add_internal(name, value)
-}
-
- - - -
- - - -## Function `remove` - -Remove the key from the Display. - - -

-public entry fun remove<T: key>(self: &mut display::Display<T>, name: string::String)
-
- - - -
-Implementation - - -

-entry public fun remove<T: key>(self: &mut Display<T>, name: String) \{
-    self.fields.remove(&name);
-}
-
- - - -
- - - -## Function `is_authorized` - -Authorization check; can be performed externally to implement protection rules for Display. - - -

-public fun is_authorized<T: key>(pub: &package::Publisher): bool
-
- - - -
-Implementation - - -

-public fun is_authorized<T: key>(pub: &Publisher): bool \{
-    pub.from_package<T>()
-}
-
- - - -
- - - -## Function `version` - -Read the -version field. - - -

-public fun version<T: key>(d: &display::Display<T>): u16
-
- - - -
-Implementation - - -

-public fun version<T: key>(d: &Display<T>): u16 \{
-    d.version
-}
-
- - - -
- - - -## Function `fields` - -Read the -fields field. - - -

-public fun fields<T: key>(d: &display::Display<T>): &vec_map::VecMap<string::String, string::String>
-
- - - -
-Implementation - - -

-public fun fields<T: key>(d: &Display<T>): &VecMap<String, String> \{
-    &d.fields
-}
-
- - - -
- - - -## Function `create_internal` - -Internal function to create a new -Display<T>. - - -

-fun create_internal<T: key>(ctx: &mut tx_context::TxContext): display::Display<T>
-
- - - -
-Implementation - - -

-fun create_internal<T: key>(ctx: &mut TxContext): Display<T> \{
-    let uid = object::new(ctx);
-
-    event::emit(DisplayCreated<T> \{
-        id: uid.to_inner()
-    });
-
-    Display \{
-        id: uid,
-        fields: vec_map::empty(),
-        version: 0,
-    }
-}
-
- - - -
- - - -## Function `add_internal` - -Private method for inserting fields without security checks. - - -

-fun add_internal<T: key>(display: &mut display::Display<T>, name: string::String, value: string::String)
-
- - - -
-Implementation - - -

-fun add_internal<T: key>(display: &mut Display<T>, name: String, value: String) \{
-    display.fields.insert(name, value)
-}
-
- - - -
diff --git a/crates/iota-framework/docs/iota-framework/dynamic_field.mdx b/crates/iota-framework/docs/iota-framework/dynamic_field.mdx deleted file mode 100644 index 55c05ef1fc4..00000000000 --- a/crates/iota-framework/docs/iota-framework/dynamic_field.mdx +++ /dev/null @@ -1,669 +0,0 @@ ---- -title: Module `0x2::dynamic_field` ---- -import Link from '@docusaurus/Link'; - - -In addition to the fields declared in its type definition, a Iota object can have dynamic fields -that can be added after the object has been constructed. Unlike ordinary field names -(which are always statically declared identifiers) a dynamic field name can be any value with -the -copy, -drop, and -store abilities, e.g. an integer, a boolean, or a string. -This gives Iota programmers the flexibility to extend objects on-the-fly, and it also serves as a -building block for core collection types - - -- [Resource `Field`](#0x2_dynamic_field_Field) -- [Constants](#@Constants_0) -- [Function `add`](#0x2_dynamic_field_add) -- [Function `borrow`](#0x2_dynamic_field_borrow) -- [Function `borrow_mut`](#0x2_dynamic_field_borrow_mut) -- [Function `remove`](#0x2_dynamic_field_remove) -- [Function `exists_`](#0x2_dynamic_field_exists_) -- [Function `remove_if_exists`](#0x2_dynamic_field_remove_if_exists) -- [Function `exists_with_type`](#0x2_dynamic_field_exists_with_type) -- [Function `field_info`](#0x2_dynamic_field_field_info) -- [Function `field_info_mut`](#0x2_dynamic_field_field_info_mut) -- [Function `hash_type_and_key`](#0x2_dynamic_field_hash_type_and_key) -- [Function `add_child_object`](#0x2_dynamic_field_add_child_object) -- [Function `borrow_child_object`](#0x2_dynamic_field_borrow_child_object) -- [Function `borrow_child_object_mut`](#0x2_dynamic_field_borrow_child_object_mut) -- [Function `remove_child_object`](#0x2_dynamic_field_remove_child_object) -- [Function `has_child_object`](#0x2_dynamic_field_has_child_object) -- [Function `has_child_object_with_ty`](#0x2_dynamic_field_has_child_object_with_ty) - - -

-use 0x1::option;
-use 0x2::object;
-
- - - - - -## Resource `Field` - -Internal object used for storing the field and value - - -

-struct Field<Name: copy, drop, store, Value: store> has key
-
- - - -
-Fields - - -
-
- -id: object::UID -
-
- Determined by the hash of the object ID, the field name value and it's type, - i.e. hash(parent.id || name || Name) -
-
- -name: Name -
-
- The value for the name of this field -
-
- -value: Value -
-
- The value bound to this field -
-
- - -
- - - -## Constants - - - - -Failed to serialize the field's name - - -

-const EBCSSerializationFailure: u64 = 3;
-
- - - - - -The object added as a dynamic field was previously a shared object - - -

-const ESharedObjectOperationNotSupported: u64 = 4;
-
- - - - - -The object already has a dynamic field with this name (with the value and type specified) - - -

-const EFieldAlreadyExists: u64 = 0;
-
- - - - - -Cannot load dynamic field. -The object does not have a dynamic field with this name (with the value and type specified) - - -

-const EFieldDoesNotExist: u64 = 1;
-
- - - - - -The object has a field with that name, but the value type does not match - - -

-const EFieldTypeMismatch: u64 = 2;
-
- - - - - -## Function `add` - -Adds a dynamic field to the object -object: &mut UID at field specified by -name: Name. -Aborts with -EFieldAlreadyExists if the object already has that field with that name. - - -

-public fun add<Name: copy, drop, store, Value: store>(object: &mut object::UID, name: Name, value: Value)
-
- - - -
-Implementation - - -

-public fun add<Name: copy + drop + store, Value: store>(
-    // we use &mut UID in several spots for access control
-    object: &mut UID,
-    name: Name,
-    value: Value,
-) \{
-    let object_addr = object.to_address();
-    let hash = hash_type_and_key(object_addr, name);
-    assert!(!has_child_object(object_addr, hash), EFieldAlreadyExists);
-    let field = Field \{
-        id: object::new_uid_from_hash(hash),
-        name,
-        value,
-    };
-    add_child_object(object_addr, field)
-}
-
- - - -
- - - -## Function `borrow` - -Immutably borrows the -objects dynamic field with the name specified by -name: Name. -Aborts with -EFieldDoesNotExist if the object does not have a field with that name. -Aborts with -EFieldTypeMismatch if the field exists, but the value does not have the specified -type. - - -

-public fun borrow<Name: copy, drop, store, Value: store>(object: &object::UID, name: Name): &Value
-
- - - -
-Implementation - - -

-public fun borrow<Name: copy + drop + store, Value: store>(
-    object: &UID,
-    name: Name,
-): &Value \{
-    let object_addr = object.to_address();
-    let hash = hash_type_and_key(object_addr, name);
-    let field = borrow_child_object<Field<Name, Value>>(object, hash);
-    &field.value
-}
-
- - - -
- - - -## Function `borrow_mut` - -Mutably borrows the -objects dynamic field with the name specified by -name: Name. -Aborts with -EFieldDoesNotExist if the object does not have a field with that name. -Aborts with -EFieldTypeMismatch if the field exists, but the value does not have the specified -type. - - -

-public fun borrow_mut<Name: copy, drop, store, Value: store>(object: &mut object::UID, name: Name): &mut Value
-
- - - -
-Implementation - - -

-public fun borrow_mut<Name: copy + drop + store, Value: store>(
-    object: &mut UID,
-    name: Name,
-): &mut Value \{
-    let object_addr = object.to_address();
-    let hash = hash_type_and_key(object_addr, name);
-    let field = borrow_child_object_mut<Field<Name, Value>>(object, hash);
-    &mut field.value
-}
-
- - - -
- - - -## Function `remove` - -Removes the -objects dynamic field with the name specified by -name: Name and returns the -bound value. -Aborts with -EFieldDoesNotExist if the object does not have a field with that name. -Aborts with -EFieldTypeMismatch if the field exists, but the value does not have the specified -type. - - -

-public fun remove<Name: copy, drop, store, Value: store>(object: &mut object::UID, name: Name): Value
-
- - - -
-Implementation - - -

-public fun remove<Name: copy + drop + store, Value: store>(
-    object: &mut UID,
-    name: Name,
-): Value \{
-    let object_addr = object.to_address();
-    let hash = hash_type_and_key(object_addr, name);
-    let Field \{ id, name: _, value } = remove_child_object<Field<Name, Value>>(object_addr, hash);
-    id.delete();
-    value
-}
-
- - - -
- - - -## Function `exists_` - -Returns true if and only if the -object has a dynamic field with the name specified by - -name: Name but without specifying the -Value type - - -

-public fun exists_<Name: copy, drop, store>(object: &object::UID, name: Name): bool
-
- - - -
-Implementation - - -

-public fun exists_<Name: copy + drop + store>(
-    object: &UID,
-    name: Name,
-): bool \{
-    let object_addr = object.to_address();
-    let hash = hash_type_and_key(object_addr, name);
-    has_child_object(object_addr, hash)
-}
-
- - - -
- - - -## Function `remove_if_exists` - -Removes the dynamic field if it exists. Returns the -some(Value) if it exists or none otherwise. - - -

-public fun remove_if_exists<Name: copy, drop, store, Value: store>(object: &mut object::UID, name: Name): option::Option<Value>
-
- - - -
-Implementation - - -

-public fun remove_if_exists<Name: copy + drop + store, Value: store>(
-    object: &mut UID,
-    name: Name
-): Option<Value> \{
-    if (exists_<Name>(object, name)) \{
-        option::some(remove(object, name))
-    } else \{
-        option::none()
-    }
-}
-
- - - -
- - - -## Function `exists_with_type` - -Returns true if and only if the -object has a dynamic field with the name specified by - -name: Name with an assigned value of type -Value. - - -

-public fun exists_with_type<Name: copy, drop, store, Value: store>(object: &object::UID, name: Name): bool
-
- - - -
-Implementation - - -

-public fun exists_with_type<Name: copy + drop + store, Value: store>(
-    object: &UID,
-    name: Name,
-): bool \{
-    let object_addr = object.to_address();
-    let hash = hash_type_and_key(object_addr, name);
-    has_child_object_with_ty<Field<Name, Value>>(object_addr, hash)
-}
-
- - - -
- - - -## Function `field_info` - - - -

-public(friend) fun field_info<Name: copy, drop, store>(object: &object::UID, name: Name): (&object::UID, address)
-
- - - -
-Implementation - - -

-public(package) fun field_info<Name: copy + drop + store>(
-    object: &UID,
-    name: Name,
-): (&UID, address) \{
-    let object_addr = object.to_address();
-    let hash = hash_type_and_key(object_addr, name);
-    let Field \{ id, name: _, value } = borrow_child_object<Field<Name, ID>>(object, hash);
-    (id, value.to_address())
-}
-
- - - -
- - - -## Function `field_info_mut` - - - -

-public(friend) fun field_info_mut<Name: copy, drop, store>(object: &mut object::UID, name: Name): (&mut object::UID, address)
-
- - - -
-Implementation - - -

-public(package) fun field_info_mut<Name: copy + drop + store>(
-    object: &mut UID,
-    name: Name,
-): (&mut UID, address) \{
-    let object_addr = object.to_address();
-    let hash = hash_type_and_key(object_addr, name);
-    let Field \{ id, name: _, value } = borrow_child_object_mut<Field<Name, ID>>(object, hash);
-    (id, value.to_address())
-}
-
- - - -
- - - -## Function `hash_type_and_key` - -May abort with -EBCSSerializationFailure. - - -

-public(friend) fun hash_type_and_key<K: copy, drop, store>(parent: address, k: K): address
-
- - - -
-Implementation - - -

-public(package) native fun hash_type_and_key<K: copy + drop + store>(parent: address, k: K): address;
-
- - - -
- - - -## Function `add_child_object` - - - -

-public(friend) fun add_child_object<Child: key>(parent: address, child: Child)
-
- - - -
-Implementation - - -

-public(package) native fun add_child_object<Child: key>(parent: address, child: Child);
-
- - - -
- - - -## Function `borrow_child_object` - -throws -EFieldDoesNotExist if a child does not exist with that ID -or throws -EFieldTypeMismatch if the type does not match, -and may also abort with -EBCSSerializationFailure -we need two versions to return a reference or a mutable reference - - -

-public(friend) fun borrow_child_object<Child: key>(object: &object::UID, id: address): &Child
-
- - - -
-Implementation - - -

-public(package) native fun borrow_child_object<Child: key>(object: &UID, id: address): &Child;
-
- - - -
- - - -## Function `borrow_child_object_mut` - - - -

-public(friend) fun borrow_child_object_mut<Child: key>(object: &mut object::UID, id: address): &mut Child
-
- - - -
-Implementation - - -

-public(package) native fun borrow_child_object_mut<Child: key>(object: &mut UID, id: address): &mut Child;
-
- - - -
- - - -## Function `remove_child_object` - -throws -EFieldDoesNotExist if a child does not exist with that ID -or throws -EFieldTypeMismatch if the type does not match, -and may also abort with -EBCSSerializationFailure. - - -

-public(friend) fun remove_child_object<Child: key>(parent: address, id: address): Child
-
- - - -
-Implementation - - -

-public(package) native fun remove_child_object<Child: key>(parent: address, id: address): Child;
-
- - - -
- - - -## Function `has_child_object` - - - -

-public(friend) fun has_child_object(parent: address, id: address): bool
-
- - - -
-Implementation - - -

-public(package) native fun has_child_object(parent: address, id: address): bool;
-
- - - -
- - - -## Function `has_child_object_with_ty` - - - -

-public(friend) fun has_child_object_with_ty<Child: key>(parent: address, id: address): bool
-
- - - -
-Implementation - - -

-public(package) native fun has_child_object_with_ty<Child: key>(parent: address, id: address): bool;
-
- - - -
diff --git a/crates/iota-framework/docs/iota-framework/dynamic_object_field.mdx b/crates/iota-framework/docs/iota-framework/dynamic_object_field.mdx deleted file mode 100644 index f8e5998efbf..00000000000 --- a/crates/iota-framework/docs/iota-framework/dynamic_object_field.mdx +++ /dev/null @@ -1,325 +0,0 @@ ---- -title: Module `0x2::dynamic_object_field` ---- -import Link from '@docusaurus/Link'; - - -Similar to -iota::dynamic_field, this module allows for the access of dynamic fields. But -unlike, -iota::dynamic_field the values bound to these dynamic fields _must_ be objects -themselves. This allows for the objects to still exist within in storage, which may be important -for external tools. The difference is otherwise not observable from within Move. - - -- [Struct `Wrapper`](#0x2_dynamic_object_field_Wrapper) -- [Function `add`](#0x2_dynamic_object_field_add) -- [Function `borrow`](#0x2_dynamic_object_field_borrow) -- [Function `borrow_mut`](#0x2_dynamic_object_field_borrow_mut) -- [Function `remove`](#0x2_dynamic_object_field_remove) -- [Function `exists_`](#0x2_dynamic_object_field_exists_) -- [Function `exists_with_type`](#0x2_dynamic_object_field_exists_with_type) -- [Function `id`](#0x2_dynamic_object_field_id) - - -

-use 0x1::option;
-use 0x2::dynamic_field;
-use 0x2::object;
-
- - - - - -## Struct `Wrapper` - - - -

-struct Wrapper<Name> has copy, drop, store
-
- - - -
-Fields - - -
-
- -name: Name -
-
- -
-
- - -
- - - -## Function `add` - -Adds a dynamic object field to the object -object: &mut UID at field specified by -name: Name. -Aborts with -EFieldAlreadyExists if the object already has that field with that name. - - -

-public fun add<Name: copy, drop, store, Value: store, key>(object: &mut object::UID, name: Name, value: Value)
-
- - - -
-Implementation - - -

-public fun add<Name: copy + drop + store, Value: key + store>(
-    // we use &mut UID in several spots for access control
-    object: &mut UID,
-    name: Name,
-    value: Value,
-) \{
-    let key = Wrapper \{ name };
-    let id = object::id(&value);
-    field::add(object, key, id);
-    let (field, _) = field::field_info<Wrapper<Name>>(object, key);
-    add_child_object(field.to_address(), value);
-}
-
- - - -
- - - -## Function `borrow` - -Immutably borrows the -objects dynamic object field with the name specified by -name: Name. -Aborts with -EFieldDoesNotExist if the object does not have a field with that name. -Aborts with -EFieldTypeMismatch if the field exists, but the value object does not have the -specified type. - - -

-public fun borrow<Name: copy, drop, store, Value: store, key>(object: &object::UID, name: Name): &Value
-
- - - -
-Implementation - - -

-public fun borrow<Name: copy + drop + store, Value: key + store>(
-    object: &UID,
-    name: Name,
-): &Value \{
-    let key = Wrapper \{ name };
-    let (field, value_id) = field::field_info<Wrapper<Name>>(object, key);
-    borrow_child_object<Value>(field, value_id)
-}
-
- - - -
- - - -## Function `borrow_mut` - -Mutably borrows the -objects dynamic object field with the name specified by -name: Name. -Aborts with -EFieldDoesNotExist if the object does not have a field with that name. -Aborts with -EFieldTypeMismatch if the field exists, but the value object does not have the -specified type. - - -

-public fun borrow_mut<Name: copy, drop, store, Value: store, key>(object: &mut object::UID, name: Name): &mut Value
-
- - - -
-Implementation - - -

-public fun borrow_mut<Name: copy + drop + store, Value: key + store>(
-    object: &mut UID,
-    name: Name,
-): &mut Value \{
-    let key = Wrapper \{ name };
-    let (field, value_id) = field::field_info_mut<Wrapper<Name>>(object, key);
-    borrow_child_object_mut<Value>(field, value_id)
-}
-
- - - -
- - - -## Function `remove` - -Removes the -objects dynamic object field with the name specified by -name: Name and returns -the bound object. -Aborts with -EFieldDoesNotExist if the object does not have a field with that name. -Aborts with -EFieldTypeMismatch if the field exists, but the value object does not have the -specified type. - - -

-public fun remove<Name: copy, drop, store, Value: store, key>(object: &mut object::UID, name: Name): Value
-
- - - -
-Implementation - - -

-public fun remove<Name: copy + drop + store, Value: key + store>(
-    object: &mut UID,
-    name: Name,
-): Value \{
-    let key = Wrapper \{ name };
-    let (field, value_id) = field::field_info<Wrapper<Name>>(object, key);
-    let value = remove_child_object<Value>(field.to_address(), value_id);
-    field::remove<Wrapper<Name>, ID>(object, key);
-    value
-}
-
- - - -
- - - -## Function `exists_` - -Returns true if and only if the -object has a dynamic object field with the name specified by - -name: Name. - - -

-public fun exists_<Name: copy, drop, store>(object: &object::UID, name: Name): bool
-
- - - -
-Implementation - - -

-public fun exists_<Name: copy + drop + store>(
-    object: &UID,
-    name: Name,
-): bool \{
-    let key = Wrapper \{ name };
-    field::exists_with_type<Wrapper<Name>, ID>(object, key)
-}
-
- - - -
- - - -## Function `exists_with_type` - -Returns true if and only if the -object has a dynamic field with the name specified by - -name: Name with an assigned value of type -Value. - - -

-public fun exists_with_type<Name: copy, drop, store, Value: store, key>(object: &object::UID, name: Name): bool
-
- - - -
-Implementation - - -

-public fun exists_with_type<Name: copy + drop + store, Value: key + store>(
-    object: &UID,
-    name: Name,
-): bool \{
-    let key = Wrapper \{ name };
-    if (!field::exists_with_type<Wrapper<Name>, ID>(object, key)) return false;
-    let (field, value_id) = field::field_info<Wrapper<Name>>(object, key);
-    field::has_child_object_with_ty<Value>(field.to_address(), value_id)
-}
-
- - - -
- - - -## Function `id` - -Returns the ID of the object associated with the dynamic object field -Returns none otherwise - - -

-public fun id<Name: copy, drop, store>(object: &object::UID, name: Name): option::Option<object::ID>
-
- - - -
-Implementation - - -

-public fun id<Name: copy + drop + store>(
-    object: &UID,
-    name: Name,
-): Option<ID> \{
-    let key = Wrapper \{ name };
-    if (!field::exists_with_type<Wrapper<Name>, ID>(object, key)) return option::none();
-    let (_field, value_addr) = field::field_info<Wrapper<Name>>(object, key);
-    option::some(value_addr.to_id())
-}
-
- - - -
diff --git a/crates/iota-framework/docs/iota-framework/ecdsa_k1.mdx b/crates/iota-framework/docs/iota-framework/ecdsa_k1.mdx deleted file mode 100644 index 1d7cf33c8db..00000000000 --- a/crates/iota-framework/docs/iota-framework/ecdsa_k1.mdx +++ /dev/null @@ -1,175 +0,0 @@ ---- -title: Module `0x2::ecdsa_k1` ---- -import Link from '@docusaurus/Link'; - - - - -- [Constants](#@Constants_0) -- [Function `secp256k1_ecrecover`](#0x2_ecdsa_k1_secp256k1_ecrecover) -- [Function `decompress_pubkey`](#0x2_ecdsa_k1_decompress_pubkey) -- [Function `secp256k1_verify`](#0x2_ecdsa_k1_secp256k1_verify) - - -

-
- - - - - -## Constants - - - - -Error if the public key cannot be recovered from the signature. - - -

-const EFailToRecoverPubKey: u64 = 0;
-
- - - - - -Error if the public key is invalid. - - -

-const EInvalidPubKey: u64 = 2;
-
- - - - - -Error if the signature is invalid. - - -

-const EInvalidSignature: u64 = 1;
-
- - - - - -Hash function name that are valid for ecrecover and secp256k1_verify. - - -

-const KECCAK256: u8 = 0;
-
- - - - - - - -

-const SHA256: u8 = 1;
-
- - - - - -## Function `secp256k1_ecrecover` - -@param signature: A 65-bytes signature in form (r, s, v) that is signed using -Secp256k1. Reference implementation on signature generation using RFC6979: -https://github.com/MystenLabs/narwhal/blob/5d6f6df8ccee94446ff88786c0dbbc98be7cfc09/crypto/src/secp256k1.rs -The accepted v values are {0, 1, 2, 3}. -@param msg: The message that the signature is signed against, this is raw message without hashing. -@param hash: The hash function used to hash the message when signing. - -If the signature is valid, return the corresponding recovered Secpk256k1 public -key, otherwise throw error. This is similar to ecrecover in Ethereum, can only be -applied to Secp256k1 signatures. May abort with -EFailToRecoverPubKey or -EInvalidSignature. - - -

-public fun secp256k1_ecrecover(signature: &vector<u8>, msg: &vector<u8>, hash: u8): vector<u8>
-
- - - -
-Implementation - - -

-public native fun secp256k1_ecrecover(signature: &vector<u8>, msg: &vector<u8>, hash: u8): vector<u8>;
-
- - - -
- - - -## Function `decompress_pubkey` - -@param pubkey: A 33-bytes compressed public key, a prefix either 0x02 or 0x03 and a 256-bit integer. - -If the compressed public key is valid, return the 65-bytes uncompressed public key, -otherwise throw error. May abort with -EInvalidPubKey. - - -

-public fun decompress_pubkey(pubkey: &vector<u8>): vector<u8>
-
- - - -
-Implementation - - -

-public native fun decompress_pubkey(pubkey: &vector<u8>): vector<u8>;
-
- - - -
- - - -## Function `secp256k1_verify` - -@param signature: A 64-bytes signature in form (r, s) that is signed using -Secp256k1. This is an non-recoverable signature without recovery id. -Reference implementation on signature generation using RFC6979: -https://github.com/MystenLabs/fastcrypto/blob/74aec4886e62122a5b769464c2bea5f803cf8ecc/fastcrypto/src/secp256k1/mod.rs#L193 -@param public_key: The public key to verify the signature against -@param msg: The message that the signature is signed against, this is raw message without hashing. -@param hash: The hash function used to hash the message when signing. - -If the signature is valid to the pubkey and hashed message, return true. Else false. - - -

-public fun secp256k1_verify(signature: &vector<u8>, public_key: &vector<u8>, msg: &vector<u8>, hash: u8): bool
-
- - - -
-Implementation - - -

-public native fun secp256k1_verify(signature: &vector<u8>, public_key: &vector<u8>, msg: &vector<u8>, hash: u8): bool;
-
- - - -
diff --git a/crates/iota-framework/docs/iota-framework/ecdsa_r1.mdx b/crates/iota-framework/docs/iota-framework/ecdsa_r1.mdx deleted file mode 100644 index 4d5aab96873..00000000000 --- a/crates/iota-framework/docs/iota-framework/ecdsa_r1.mdx +++ /dev/null @@ -1,134 +0,0 @@ ---- -title: Module `0x2::ecdsa_r1` ---- -import Link from '@docusaurus/Link'; - - - - -- [Constants](#@Constants_0) -- [Function `secp256r1_ecrecover`](#0x2_ecdsa_r1_secp256r1_ecrecover) -- [Function `secp256r1_verify`](#0x2_ecdsa_r1_secp256r1_verify) - - -

-
- - - - - -## Constants - - - - -Error if the public key cannot be recovered from the signature. - - -

-const EFailToRecoverPubKey: u64 = 0;
-
- - - - - -Error if the signature is invalid. - - -

-const EInvalidSignature: u64 = 1;
-
- - - - - -Hash function name that are valid for ecrecover and secp256k1_verify. - - -

-const KECCAK256: u8 = 0;
-
- - - - - - - -

-const SHA256: u8 = 1;
-
- - - - - -## Function `secp256r1_ecrecover` - -@param signature: A 65-bytes signature in form (r, s, v) that is signed using -Secp256r1. Reference implementation on signature generation using RFC6979: -https://github.com/MystenLabs/fastcrypto/blob/74aec4886e62122a5b769464c2bea5f803cf8ecc/fastcrypto/src/secp256r1/mod.rs -The accepted v values are {0, 1, 2, 3}. -@param msg: The message that the signature is signed against, this is raw message without hashing. -@param hash: The u8 representing the name of hash function used to hash the message when signing. - -If the signature is valid, return the corresponding recovered Secpk256r1 public -key, otherwise throw error. This is similar to ecrecover in Ethereum, can only be -applied to Secp256r1 signatures. May fail with -EFailToRecoverPubKey or -EInvalidSignature. - - -

-public fun secp256r1_ecrecover(signature: &vector<u8>, msg: &vector<u8>, hash: u8): vector<u8>
-
- - - -
-Implementation - - -

-public native fun secp256r1_ecrecover(signature: &vector<u8>, msg: &vector<u8>, hash: u8): vector<u8>;
-
- - - -
- - - -## Function `secp256r1_verify` - -@param signature: A 64-bytes signature in form (r, s) that is signed using -Secp256r1. This is an non-recoverable signature without recovery id. -Reference implementation on signature generation using RFC6979: -https://github.com/MystenLabs/fastcrypto/blob/74aec4886e62122a5b769464c2bea5f803cf8ecc/fastcrypto/src/secp256r1/mod.rs -@param public_key: The public key to verify the signature against -@param msg: The message that the signature is signed against, this is raw message without hashing. -@param hash: The u8 representing the name of hash function used to hash the message when signing. - -If the signature is valid to the pubkey and hashed message, return true. Else false. - - -

-public fun secp256r1_verify(signature: &vector<u8>, public_key: &vector<u8>, msg: &vector<u8>, hash: u8): bool
-
- - - -
-Implementation - - -

-public native fun secp256r1_verify(signature: &vector<u8>, public_key: &vector<u8>, msg: &vector<u8>, hash: u8): bool;
-
- - - -
diff --git a/crates/iota-framework/docs/iota-framework/ecvrf.mdx b/crates/iota-framework/docs/iota-framework/ecvrf.mdx deleted file mode 100644 index dd39e464148..00000000000 --- a/crates/iota-framework/docs/iota-framework/ecvrf.mdx +++ /dev/null @@ -1,83 +0,0 @@ ---- -title: Module `0x2::ecvrf` ---- -import Link from '@docusaurus/Link'; - - - - -- [Constants](#@Constants_0) -- [Function `ecvrf_verify`](#0x2_ecvrf_ecvrf_verify) - - -

-
- - - - - -## Constants - - - - - - -

-const EInvalidHashLength: u64 = 1;
-
- - - - - - - -

-const EInvalidProofEncoding: u64 = 3;
-
- - - - - - - -

-const EInvalidPublicKeyEncoding: u64 = 2;
-
- - - - - -## Function `ecvrf_verify` - -@param hash: The hash/output from a ECVRF to be verified. -@param alpha_string: Input/seed to the ECVRF used to generate the output. -@param public_key: The public key corresponding to the private key used to generate the output. -@param proof: The proof of validity of the output. -Verify a proof for a Ristretto ECVRF. Returns true if the proof is valid and corresponds to the given output. May abort with -EInvalidHashLength, -EInvalidPublicKeyEncoding or -EInvalidProofEncoding. - - -

-public fun ecvrf_verify(hash: &vector<u8>, alpha_string: &vector<u8>, public_key: &vector<u8>, proof: &vector<u8>): bool
-
- - - -
-Implementation - - -

-public native fun ecvrf_verify(hash: &vector<u8>, alpha_string: &vector<u8>, public_key: &vector<u8>, proof: &vector<u8>): bool;
-
- - - -
diff --git a/crates/iota-framework/docs/iota-framework/ed25519.mdx b/crates/iota-framework/docs/iota-framework/ed25519.mdx deleted file mode 100644 index fb051426486..00000000000 --- a/crates/iota-framework/docs/iota-framework/ed25519.mdx +++ /dev/null @@ -1,45 +0,0 @@ ---- -title: Module `0x2::ed25519` ---- -import Link from '@docusaurus/Link'; - - - - -- [Function `ed25519_verify`](#0x2_ed25519_ed25519_verify) - - -

-
- - - - - -## Function `ed25519_verify` - -@param signature: 32-byte signature that is a point on the Ed25519 elliptic curve. -@param public_key: 32-byte signature that is a point on the Ed25519 elliptic curve. -@param msg: The message that we test the signature against. - -If the signature is a valid Ed25519 signature of the message and public key, return true. -Otherwise, return false. - - -

-public fun ed25519_verify(signature: &vector<u8>, public_key: &vector<u8>, msg: &vector<u8>): bool
-
- - - -
-Implementation - - -

-public native fun ed25519_verify(signature: &vector<u8>, public_key: &vector<u8>, msg: &vector<u8>): bool;
-
- - - -
diff --git a/crates/iota-framework/docs/iota-framework/event.mdx b/crates/iota-framework/docs/iota-framework/event.mdx deleted file mode 100644 index f52a2b3a822..00000000000 --- a/crates/iota-framework/docs/iota-framework/event.mdx +++ /dev/null @@ -1,76 +0,0 @@ ---- -title: Module `0x2::event` ---- -import Link from '@docusaurus/Link'; - - -Events module. Defines the -iota::event::emit function which -creates and sends a custom MoveEvent as a part of the effects -certificate of the transaction. - -Every MoveEvent has the following properties: -- sender -- type signature ( -T) -- event data (the value of -T) -- timestamp (local to a node) -- transaction digest - -Example: -``` -module my::marketplace { -use iota::event; -/* ... */ -struct ItemPurchased has copy, drop { -item_id: ID, buyer: address -} -entry fun buy(/* .... */) { -/* ... */ -event::emit(ItemPurchased { item_id: ..., buyer: .... }) -} -} -``` - - -- [Function `emit`](#0x2_event_emit) - - -

-
- - - - - -## Function `emit` - -Emit a custom Move event, sending the data offchain. - -Used for creating custom indexes and tracking onchain -activity in a way that suits a specific application the most. - -The type -T is the main way to index the event, and can contain -phantom parameters, eg -emit(MyEvent<phantom T>). - - -

-public fun emit<T: copy, drop>(event: T)
-
- - - -
-Implementation - - -

-public native fun emit<T: copy + drop>(event: T);
-
- - - -
diff --git a/crates/iota-framework/docs/iota-framework/groth16.mdx b/crates/iota-framework/docs/iota-framework/groth16.mdx deleted file mode 100644 index 2ddaff828e2..00000000000 --- a/crates/iota-framework/docs/iota-framework/groth16.mdx +++ /dev/null @@ -1,516 +0,0 @@ ---- -title: Module `0x2::groth16` ---- -import Link from '@docusaurus/Link'; - - - - -- [Struct `Curve`](#0x2_groth16_Curve) -- [Struct `PreparedVerifyingKey`](#0x2_groth16_PreparedVerifyingKey) -- [Struct `PublicProofInputs`](#0x2_groth16_PublicProofInputs) -- [Struct `ProofPoints`](#0x2_groth16_ProofPoints) -- [Constants](#@Constants_0) -- [Function `bls12381`](#0x2_groth16_bls12381) -- [Function `bn254`](#0x2_groth16_bn254) -- [Function `pvk_from_bytes`](#0x2_groth16_pvk_from_bytes) -- [Function `pvk_to_bytes`](#0x2_groth16_pvk_to_bytes) -- [Function `public_proof_inputs_from_bytes`](#0x2_groth16_public_proof_inputs_from_bytes) -- [Function `proof_points_from_bytes`](#0x2_groth16_proof_points_from_bytes) -- [Function `prepare_verifying_key`](#0x2_groth16_prepare_verifying_key) -- [Function `prepare_verifying_key_internal`](#0x2_groth16_prepare_verifying_key_internal) -- [Function `verify_groth16_proof`](#0x2_groth16_verify_groth16_proof) -- [Function `verify_groth16_proof_internal`](#0x2_groth16_verify_groth16_proof_internal) - - -

-
- - - - - -## Struct `Curve` - -Represents an elliptic curve construction to be used in the verifier. Currently we support BLS12-381 and BN254. -This should be given as the first parameter to -prepare_verifying_key or -verify_groth16_proof. - - -

-struct Curve has copy, drop, store
-
- - - -
-Fields - - -
-
- -id: u8 -
-
- -
-
- - -
- - - -## Struct `PreparedVerifyingKey` - -A -PreparedVerifyingKey consisting of four components in serialized form. - - -

-struct PreparedVerifyingKey has copy, drop, store
-
- - - -
-Fields - - -
-
- -vk_gamma_abc_g1_bytes: vector<u8> -
-
- -
-
- -alpha_g1_beta_g2_bytes: vector<u8> -
-
- -
-
- -gamma_g2_neg_pc_bytes: vector<u8> -
-
- -
-
- -delta_g2_neg_pc_bytes: vector<u8> -
-
- -
-
- - -
- - - -## Struct `PublicProofInputs` - -A -PublicProofInputs wrapper around its serialized bytes. - - -

-struct PublicProofInputs has copy, drop, store
-
- - - -
-Fields - - -
-
- -bytes: vector<u8> -
-
- -
-
- - -
- - - -## Struct `ProofPoints` - -A -ProofPoints wrapper around the serialized form of three proof points. - - -

-struct ProofPoints has copy, drop, store
-
- - - -
-Fields - - -
-
- -bytes: vector<u8> -
-
- -
-
- - -
- - - -## Constants - - - - - - -

-const EInvalidCurve: u64 = 1;
-
- - - - - - - -

-const EInvalidVerifyingKey: u64 = 0;
-
- - - - - - - -

-const ETooManyPublicInputs: u64 = 2;
-
- - - - - -## Function `bls12381` - -Return the -Curve value indicating that the BLS12-381 construction should be used in a given function. - - -

-public fun bls12381(): groth16::Curve
-
- - - -
-Implementation - - -

-public fun bls12381(): Curve \{ Curve \{ id: 0 } }
-
- - - -
- - - -## Function `bn254` - -Return the -Curve value indicating that the BN254 construction should be used in a given function. - - -

-public fun bn254(): groth16::Curve
-
- - - -
-Implementation - - -

-public fun bn254(): Curve \{ Curve \{ id: 1 } }
-
- - - -
- - - -## Function `pvk_from_bytes` - -Creates a -PreparedVerifyingKey from bytes. - - -

-public fun pvk_from_bytes(vk_gamma_abc_g1_bytes: vector<u8>, alpha_g1_beta_g2_bytes: vector<u8>, gamma_g2_neg_pc_bytes: vector<u8>, delta_g2_neg_pc_bytes: vector<u8>): groth16::PreparedVerifyingKey
-
- - - -
-Implementation - - -

-public fun pvk_from_bytes(vk_gamma_abc_g1_bytes: vector<u8>, alpha_g1_beta_g2_bytes: vector<u8>, gamma_g2_neg_pc_bytes: vector<u8>, delta_g2_neg_pc_bytes: vector<u8>): PreparedVerifyingKey \{
-    PreparedVerifyingKey \{
-        vk_gamma_abc_g1_bytes,
-        alpha_g1_beta_g2_bytes,
-        gamma_g2_neg_pc_bytes,
-        delta_g2_neg_pc_bytes
-    }
-}
-
- - - -
- - - -## Function `pvk_to_bytes` - -Returns bytes of the four components of the -PreparedVerifyingKey. - - -

-public fun pvk_to_bytes(pvk: groth16::PreparedVerifyingKey): vector<vector<u8>>
-
- - - -
-Implementation - - -

-public fun pvk_to_bytes(pvk: PreparedVerifyingKey): vector<vector<u8>> \{
-    vector[
-        pvk.vk_gamma_abc_g1_bytes,
-        pvk.alpha_g1_beta_g2_bytes,
-        pvk.gamma_g2_neg_pc_bytes,
-        pvk.delta_g2_neg_pc_bytes,
-    ]
-}
-
- - - -
- - - -## Function `public_proof_inputs_from_bytes` - -Creates a -PublicProofInputs wrapper from bytes. - - -

-public fun public_proof_inputs_from_bytes(bytes: vector<u8>): groth16::PublicProofInputs
-
- - - -
-Implementation - - -

-public fun public_proof_inputs_from_bytes(bytes: vector<u8>): PublicProofInputs \{
-    PublicProofInputs \{ bytes }
-}
-
- - - -
- - - -## Function `proof_points_from_bytes` - -Creates a Groth16 -ProofPoints from bytes. - - -

-public fun proof_points_from_bytes(bytes: vector<u8>): groth16::ProofPoints
-
- - - -
-Implementation - - -

-public fun proof_points_from_bytes(bytes: vector<u8>): ProofPoints \{
-    ProofPoints \{ bytes }
-}
-
- - - -
- - - -## Function `prepare_verifying_key` - -@param curve: What elliptic curve construction to use. See -bls12381 and -bn254. -@param verifying_key: An Arkworks canonical compressed serialization of a verifying key. - -Returns four vectors of bytes representing the four components of a prepared verifying key. -This step computes one pairing e(P, Q), and binds the verification to one particular proof statement. -This can be used as inputs for the -verify_groth16_proof function. - - -

-public fun prepare_verifying_key(curve: &groth16::Curve, verifying_key: &vector<u8>): groth16::PreparedVerifyingKey
-
- - - -
-Implementation - - -

-public fun prepare_verifying_key(curve: &Curve, verifying_key: &vector<u8>): PreparedVerifyingKey \{
-    prepare_verifying_key_internal(curve.id, verifying_key)
-}
-
- - - -
- - - -## Function `prepare_verifying_key_internal` - -Native functions that flattens the inputs into an array and passes to the Rust native function. May abort with -EInvalidVerifyingKey or -EInvalidCurve. - - -

-fun prepare_verifying_key_internal(curve: u8, verifying_key: &vector<u8>): groth16::PreparedVerifyingKey
-
- - - -
-Implementation - - -

-native fun prepare_verifying_key_internal(curve: u8, verifying_key: &vector<u8>): PreparedVerifyingKey;
-
- - - -
- - - -## Function `verify_groth16_proof` - -@param curve: What elliptic curve construction to use. See the -bls12381 and -bn254 functions. -@param prepared_verifying_key: Consists of four vectors of bytes representing the four components of a prepared verifying key. -@param public_proof_inputs: Represent inputs that are public. -@param proof_points: Represent three proof points. - -Returns a boolean indicating whether the proof is valid. - - -

-public fun verify_groth16_proof(curve: &groth16::Curve, prepared_verifying_key: &groth16::PreparedVerifyingKey, public_proof_inputs: &groth16::PublicProofInputs, proof_points: &groth16::ProofPoints): bool
-
- - - -
-Implementation - - -

-public fun verify_groth16_proof(curve: &Curve, prepared_verifying_key: &PreparedVerifyingKey, public_proof_inputs: &PublicProofInputs, proof_points: &ProofPoints): bool \{
-    verify_groth16_proof_internal(
-        curve.id,
-        &prepared_verifying_key.vk_gamma_abc_g1_bytes,
-        &prepared_verifying_key.alpha_g1_beta_g2_bytes,
-        &prepared_verifying_key.gamma_g2_neg_pc_bytes,
-        &prepared_verifying_key.delta_g2_neg_pc_bytes,
-        &public_proof_inputs.bytes,
-        &proof_points.bytes
-    )
-}
-
- - - -
- - - -## Function `verify_groth16_proof_internal` - -Native functions that flattens the inputs into arrays of vectors and passed to the Rust native function. May abort with -EInvalidCurve or -ETooManyPublicInputs. - - -

-fun verify_groth16_proof_internal(curve: u8, vk_gamma_abc_g1_bytes: &vector<u8>, alpha_g1_beta_g2_bytes: &vector<u8>, gamma_g2_neg_pc_bytes: &vector<u8>, delta_g2_neg_pc_bytes: &vector<u8>, public_proof_inputs: &vector<u8>, proof_points: &vector<u8>): bool
-
- - - -
-Implementation - - -

-native fun verify_groth16_proof_internal(curve: u8, vk_gamma_abc_g1_bytes: &vector<u8>, alpha_g1_beta_g2_bytes: &vector<u8>, gamma_g2_neg_pc_bytes: &vector<u8>, delta_g2_neg_pc_bytes: &vector<u8>, public_proof_inputs: &vector<u8>, proof_points: &vector<u8>): bool;
-
- - - -
diff --git a/crates/iota-framework/docs/iota-framework/group_ops.mdx b/crates/iota-framework/docs/iota-framework/group_ops.mdx deleted file mode 100644 index 19b75ebee18..00000000000 --- a/crates/iota-framework/docs/iota-framework/group_ops.mdx +++ /dev/null @@ -1,615 +0,0 @@ ---- -title: Module `0x2::group_ops` ---- -import Link from '@docusaurus/Link'; - - -Generic Move and native functions for group operations. - - -- [Struct `Element`](#0x2_group_ops_Element) -- [Constants](#@Constants_0) -- [Function `bytes`](#0x2_group_ops_bytes) -- [Function `equal`](#0x2_group_ops_equal) -- [Function `from_bytes`](#0x2_group_ops_from_bytes) -- [Function `add`](#0x2_group_ops_add) -- [Function `sub`](#0x2_group_ops_sub) -- [Function `mul`](#0x2_group_ops_mul) -- [Function `div`](#0x2_group_ops_div) -- [Function `hash_to`](#0x2_group_ops_hash_to) -- [Function `multi_scalar_multiplication`](#0x2_group_ops_multi_scalar_multiplication) -- [Function `pairing`](#0x2_group_ops_pairing) -- [Function `internal_validate`](#0x2_group_ops_internal_validate) -- [Function `internal_add`](#0x2_group_ops_internal_add) -- [Function `internal_sub`](#0x2_group_ops_internal_sub) -- [Function `internal_mul`](#0x2_group_ops_internal_mul) -- [Function `internal_div`](#0x2_group_ops_internal_div) -- [Function `internal_hash_to`](#0x2_group_ops_internal_hash_to) -- [Function `internal_multi_scalar_mul`](#0x2_group_ops_internal_multi_scalar_mul) -- [Function `internal_pairing`](#0x2_group_ops_internal_pairing) -- [Function `set_as_prefix`](#0x2_group_ops_set_as_prefix) - - -

-use 0x1::vector;
-use 0x2::bcs;
-
- - - - - -## Struct `Element` - - - -

-struct Element<T> has copy, drop, store
-
- - - -
-Fields - - -
-
- -bytes: vector<u8> -
-
- -
-
- - -
- - - -## Constants - - - - - - -

-const EInputTooLong: u64 = 2;
-
- - - - - - - -

-const EInvalidBufferLength: u64 = 3;
-
- - - - - - - -

-const EInvalidInput: u64 = 1;
-
- - - - - - - -

-const ENotSupported: u64 = 0;
-
- - - - - -## Function `bytes` - - - -

-public fun bytes<G>(e: &group_ops::Element<G>): &vector<u8>
-
- - - -
-Implementation - - -

-public fun bytes<G>(e: &Element<G>): &vector<u8> \{
-    &e.bytes
-}
-
- - - -
- - - -## Function `equal` - - - -

-public fun equal<G>(e1: &group_ops::Element<G>, e2: &group_ops::Element<G>): bool
-
- - - -
-Implementation - - -

-public fun equal<G>(e1: &Element<G>, e2: &Element<G>): bool \{
-    &e1.bytes == &e2.bytes
-}
-
- - - -
- - - -## Function `from_bytes` - - - -

-public(friend) fun from_bytes<G>(type_: u8, bytes: &vector<u8>, is_trusted: bool): group_ops::Element<G>
-
- - - -
-Implementation - - -

-public(package) fun from_bytes<G>(type_: u8, bytes: &vector<u8>, is_trusted: bool): Element<G> \{
-    assert!(is_trusted || internal_validate(type_, bytes), EInvalidInput);
-    Element<G> \{ bytes: *bytes }
-}
-
- - - -
- - - -## Function `add` - - - -

-public(friend) fun add<G>(type_: u8, e1: &group_ops::Element<G>, e2: &group_ops::Element<G>): group_ops::Element<G>
-
- - - -
-Implementation - - -

-public(package) fun add<G>(type_: u8, e1: &Element<G>, e2: &Element<G>): Element<G> \{
-    Element<G> \{ bytes: internal_add(type_, &e1.bytes, &e2.bytes) }
-}
-
- - - -
- - - -## Function `sub` - - - -

-public(friend) fun sub<G>(type_: u8, e1: &group_ops::Element<G>, e2: &group_ops::Element<G>): group_ops::Element<G>
-
- - - -
-Implementation - - -

-public(package) fun sub<G>(type_: u8, e1: &Element<G>, e2: &Element<G>): Element<G> \{
-    Element<G> \{ bytes: internal_sub(type_, &e1.bytes, &e2.bytes) }
-}
-
- - - -
- - - -## Function `mul` - - - -

-public(friend) fun mul<S, G>(type_: u8, scalar: &group_ops::Element<S>, e: &group_ops::Element<G>): group_ops::Element<G>
-
- - - -
-Implementation - - -

-public(package) fun mul<S, G>(type_: u8, scalar: &Element<S>, e: &Element<G>): Element<G> \{
-    Element<G> \{ bytes: internal_mul(type_, &scalar.bytes, &e.bytes) }
-}
-
- - - -
- - - -## Function `div` - -Fails if scalar = 0. Else returns 1/scalar * e. - - -

-public(friend) fun div<S, G>(type_: u8, scalar: &group_ops::Element<S>, e: &group_ops::Element<G>): group_ops::Element<G>
-
- - - -
-Implementation - - -

-public(package) fun div<S, G>(type_: u8, scalar: &Element<S>, e: &Element<G>): Element<G> \{
-    Element<G> \{ bytes: internal_div(type_, &scalar.bytes, &e.bytes) }
-}
-
- - - -
- - - -## Function `hash_to` - - - -

-public(friend) fun hash_to<G>(type_: u8, m: &vector<u8>): group_ops::Element<G>
-
- - - -
-Implementation - - -

-public(package) fun hash_to<G>(type_: u8, m: &vector<u8>): Element<G> \{
-    Element<G> \{ bytes: internal_hash_to(type_, m) }
-}
-
- - - -
- - - -## Function `multi_scalar_multiplication` - -Aborts with -EInputTooLong if the vectors are too long. - - -

-public(friend) fun multi_scalar_multiplication<S, G>(type_: u8, scalars: &vector<group_ops::Element<S>>, elements: &vector<group_ops::Element<G>>): group_ops::Element<G>
-
- - - -
-Implementation - - -

-public(package) fun multi_scalar_multiplication<S, G>(type_: u8, scalars: &vector<Element<S>>, elements: &vector<Element<G>>): Element<G> \{
-    assert!(scalars.length() > 0, EInvalidInput);
-    assert!(scalars.length() == elements.length(), EInvalidInput);
-
-    let mut scalars_bytes: vector<u8> = vector[];
-    let mut elements_bytes: vector<u8>  = vector[];
-    let mut i = 0;
-    while (i < scalars.length()) \{
-        let scalar_vec = scalars[i];
-        scalars_bytes.append(scalar_vec.bytes);
-        let element_vec = elements[i];
-        elements_bytes.append(element_vec.bytes);
-        i = i + 1;
-    };
-    Element<G> \{ bytes: internal_multi_scalar_mul(type_, &scalars_bytes, &elements_bytes) }
-}
-
- - - -
- - - -## Function `pairing` - - - -

-public(friend) fun pairing<G1, G2, G3>(type_: u8, e1: &group_ops::Element<G1>, e2: &group_ops::Element<G2>): group_ops::Element<G3>
-
- - - -
-Implementation - - -

-public(package) fun pairing<G1, G2, G3>(type_: u8, e1: &Element<G1>, e2: &Element<G2>): Element<G3> \{
-    Element<G3> \{ bytes: internal_pairing(type_, &e1.bytes, &e2.bytes) }
-}
-
- - - -
- - - -## Function `internal_validate` - - - -

-fun internal_validate(type_: u8, bytes: &vector<u8>): bool
-
- - - -
-Implementation - - -

-native fun internal_validate(type_: u8, bytes: &vector<u8>): bool;
-
- - - -
- - - -## Function `internal_add` - - - -

-fun internal_add(type_: u8, e1: &vector<u8>, e2: &vector<u8>): vector<u8>
-
- - - -
-Implementation - - -

-native fun internal_add(type_: u8, e1: &vector<u8>, e2: &vector<u8>): vector<u8>;
-
- - - -
- - - -## Function `internal_sub` - - - -

-fun internal_sub(type_: u8, e1: &vector<u8>, e2: &vector<u8>): vector<u8>
-
- - - -
-Implementation - - -

-native fun internal_sub(type_: u8, e1: &vector<u8>, e2: &vector<u8>): vector<u8>;
-
- - - -
- - - -## Function `internal_mul` - - - -

-fun internal_mul(type_: u8, e1: &vector<u8>, e2: &vector<u8>): vector<u8>
-
- - - -
-Implementation - - -

-native fun internal_mul(type_: u8, e1: &vector<u8>, e2: &vector<u8>): vector<u8>;
-
- - - -
- - - -## Function `internal_div` - - - -

-fun internal_div(type_: u8, e1: &vector<u8>, e2: &vector<u8>): vector<u8>
-
- - - -
-Implementation - - -

-native fun internal_div(type_: u8, e1: &vector<u8>, e2: &vector<u8>): vector<u8>;
-
- - - -
- - - -## Function `internal_hash_to` - - - -

-fun internal_hash_to(type_: u8, m: &vector<u8>): vector<u8>
-
- - - -
-Implementation - - -

-native fun internal_hash_to(type_: u8, m: &vector<u8>): vector<u8>;
-
- - - -
- - - -## Function `internal_multi_scalar_mul` - - - -

-fun internal_multi_scalar_mul(type_: u8, scalars: &vector<u8>, elements: &vector<u8>): vector<u8>
-
- - - -
-Implementation - - -

-native fun internal_multi_scalar_mul(type_: u8, scalars: &vector<u8>, elements: &vector<u8>): vector<u8>;
-
- - - -
- - - -## Function `internal_pairing` - - - -

-fun internal_pairing(type_: u8, e1: &vector<u8>, e2: &vector<u8>): vector<u8>
-
- - - -
-Implementation - - -

-native fun internal_pairing(type_: u8, e1: &vector<u8>, e2: &vector<u8>): vector<u8>;
-
- - - -
- - - -## Function `set_as_prefix` - - - -

-public(friend) fun set_as_prefix(x: u64, big_endian: bool, buffer: &mut vector<u8>)
-
- - - -
-Implementation - - -

-public(package) fun set_as_prefix(x: u64, big_endian: bool, buffer: &mut vector<u8>) \{
-    let buffer_len = buffer.length();
-    assert!(buffer_len > 7, EInvalidBufferLength);
-    let x_as_bytes = bcs::to_bytes(&x); // little endian
-    let mut i = 0;
-    while (i < 8) \{
-        let position = if (big_endian) \{ buffer_len - i - 1 } else \{ i };
-        *(&mut buffer[position]) = x_as_bytes[i];
-        i = i + 1;
-    };
-}
-
- - - -
diff --git a/crates/iota-framework/docs/iota-framework/hash.mdx b/crates/iota-framework/docs/iota-framework/hash.mdx deleted file mode 100644 index 804dabb6719..00000000000 --- a/crates/iota-framework/docs/iota-framework/hash.mdx +++ /dev/null @@ -1,70 +0,0 @@ ---- -title: Module `0x2::hash` ---- -import Link from '@docusaurus/Link'; - - -Module which defines hash functions. Note that Sha-256 and Sha3-256 is available in the std::hash module in the -standard library. - - -- [Function `blake2b256`](#0x2_hash_blake2b256) -- [Function `keccak256`](#0x2_hash_keccak256) - - -

-
- - - - - -## Function `blake2b256` - -@param data: Arbitrary binary data to hash -Hash the input bytes using Blake2b-256 and returns 32 bytes. - - -

-public fun blake2b256(data: &vector<u8>): vector<u8>
-
- - - -
-Implementation - - -

-native public fun blake2b256(data: &vector<u8>): vector<u8>;
-
- - - -
- - - -## Function `keccak256` - -@param data: Arbitrary binary data to hash -Hash the input bytes using keccak256 and returns 32 bytes. - - -

-public fun keccak256(data: &vector<u8>): vector<u8>
-
- - - -
-Implementation - - -

-native public fun keccak256(data: &vector<u8>): vector<u8>;
-
- - - -
diff --git a/crates/iota-framework/docs/iota-framework/hex.mdx b/crates/iota-framework/docs/iota-framework/hex.mdx deleted file mode 100644 index c640bf35321..00000000000 --- a/crates/iota-framework/docs/iota-framework/hex.mdx +++ /dev/null @@ -1,167 +0,0 @@ ---- -title: Module `0x2::hex` ---- -import Link from '@docusaurus/Link'; - - -HEX (Base16) encoding utility. - - -- [Constants](#@Constants_0) -- [Function `encode`](#0x2_hex_encode) -- [Function `decode`](#0x2_hex_decode) -- [Function `decode_byte`](#0x2_hex_decode_byte) - - -

-use 0x1::vector;
-
- - - - - -## Constants - - - - - - -

-const EInvalidHexLength: u64 = 0;
-
- - - - - - - -

-const ENotValidHexCharacter: u64 = 1;
-
- - - - - -Vector of Base16 values from -00 to -FF - - -

-const HEX: vector<vector<u8>> = [ByteArray([48, 48]), ByteArray([48, 49]), ByteArray([48, 50]), ByteArray([48, 51]), ByteArray([48, 52]), ByteArray([48, 53]), ByteArray([48, 54]), ByteArray([48, 55]), ByteArray([48, 56]), ByteArray([48, 57]), ByteArray([48, 97]), ByteArray([48, 98]), ByteArray([48, 99]), ByteArray([48, 100]), ByteArray([48, 101]), ByteArray([48, 102]), ByteArray([49, 48]), ByteArray([49, 49]), ByteArray([49, 50]), ByteArray([49, 51]), ByteArray([49, 52]), ByteArray([49, 53]), ByteArray([49, 54]), ByteArray([49, 55]), ByteArray([49, 56]), ByteArray([49, 57]), ByteArray([49, 97]), ByteArray([49, 98]), ByteArray([49, 99]), ByteArray([49, 100]), ByteArray([49, 101]), ByteArray([49, 102]), ByteArray([50, 48]), ByteArray([50, 49]), ByteArray([50, 50]), ByteArray([50, 51]), ByteArray([50, 52]), ByteArray([50, 53]), ByteArray([50, 54]), ByteArray([50, 55]), ByteArray([50, 56]), ByteArray([50, 57]), ByteArray([50, 97]), ByteArray([50, 98]), ByteArray([50, 99]), ByteArray([50, 100]), ByteArray([50, 101]), ByteArray([50, 102]), ByteArray([51, 48]), ByteArray([51, 49]), ByteArray([51, 50]), ByteArray([51, 51]), ByteArray([51, 52]), ByteArray([51, 53]), ByteArray([51, 54]), ByteArray([51, 55]), ByteArray([51, 56]), ByteArray([51, 57]), ByteArray([51, 97]), ByteArray([51, 98]), ByteArray([51, 99]), ByteArray([51, 100]), ByteArray([51, 101]), ByteArray([51, 102]), ByteArray([52, 48]), ByteArray([52, 49]), ByteArray([52, 50]), ByteArray([52, 51]), ByteArray([52, 52]), ByteArray([52, 53]), ByteArray([52, 54]), ByteArray([52, 55]), ByteArray([52, 56]), ByteArray([52, 57]), ByteArray([52, 97]), ByteArray([52, 98]), ByteArray([52, 99]), ByteArray([52, 100]), ByteArray([52, 101]), ByteArray([52, 102]), ByteArray([53, 48]), ByteArray([53, 49]), ByteArray([53, 50]), ByteArray([53, 51]), ByteArray([53, 52]), ByteArray([53, 53]), ByteArray([53, 54]), ByteArray([53, 55]), ByteArray([53, 56]), ByteArray([53, 57]), ByteArray([53, 97]), ByteArray([53, 98]), ByteArray([53, 99]), ByteArray([53, 100]), ByteArray([53, 101]), ByteArray([53, 102]), ByteArray([54, 48]), ByteArray([54, 49]), ByteArray([54, 50]), ByteArray([54, 51]), ByteArray([54, 52]), ByteArray([54, 53]), ByteArray([54, 54]), ByteArray([54, 55]), ByteArray([54, 56]), ByteArray([54, 57]), ByteArray([54, 97]), ByteArray([54, 98]), ByteArray([54, 99]), ByteArray([54, 100]), ByteArray([54, 101]), ByteArray([54, 102]), ByteArray([55, 48]), ByteArray([55, 49]), ByteArray([55, 50]), ByteArray([55, 51]), ByteArray([55, 52]), ByteArray([55, 53]), ByteArray([55, 54]), ByteArray([55, 55]), ByteArray([55, 56]), ByteArray([55, 57]), ByteArray([55, 97]), ByteArray([55, 98]), ByteArray([55, 99]), ByteArray([55, 100]), ByteArray([55, 101]), ByteArray([55, 102]), ByteArray([56, 48]), ByteArray([56, 49]), ByteArray([56, 50]), ByteArray([56, 51]), ByteArray([56, 52]), ByteArray([56, 53]), ByteArray([56, 54]), ByteArray([56, 55]), ByteArray([56, 56]), ByteArray([56, 57]), ByteArray([56, 97]), ByteArray([56, 98]), ByteArray([56, 99]), ByteArray([56, 100]), ByteArray([56, 101]), ByteArray([56, 102]), ByteArray([57, 48]), ByteArray([57, 49]), ByteArray([57, 50]), ByteArray([57, 51]), ByteArray([57, 52]), ByteArray([57, 53]), ByteArray([57, 54]), ByteArray([57, 55]), ByteArray([57, 56]), ByteArray([57, 57]), ByteArray([57, 97]), ByteArray([57, 98]), ByteArray([57, 99]), ByteArray([57, 100]), ByteArray([57, 101]), ByteArray([57, 102]), ByteArray([97, 48]), ByteArray([97, 49]), ByteArray([97, 50]), ByteArray([97, 51]), ByteArray([97, 52]), ByteArray([97, 53]), ByteArray([97, 54]), ByteArray([97, 55]), ByteArray([97, 56]), ByteArray([97, 57]), ByteArray([97, 97]), ByteArray([97, 98]), ByteArray([97, 99]), ByteArray([97, 100]), ByteArray([97, 101]), ByteArray([97, 102]), ByteArray([98, 48]), ByteArray([98, 49]), ByteArray([98, 50]), ByteArray([98, 51]), ByteArray([98, 52]), ByteArray([98, 53]), ByteArray([98, 54]), ByteArray([98, 55]), ByteArray([98, 56]), ByteArray([98, 57]), ByteArray([98, 97]), ByteArray([98, 98]), ByteArray([98, 99]), ByteArray([98, 100]), ByteArray([98, 101]), ByteArray([98, 102]), ByteArray([99, 48]), ByteArray([99, 49]), ByteArray([99, 50]), ByteArray([99, 51]), ByteArray([99, 52]), ByteArray([99, 53]), ByteArray([99, 54]), ByteArray([99, 55]), ByteArray([99, 56]), ByteArray([99, 57]), ByteArray([99, 97]), ByteArray([99, 98]), ByteArray([99, 99]), ByteArray([99, 100]), ByteArray([99, 101]), ByteArray([99, 102]), ByteArray([100, 48]), ByteArray([100, 49]), ByteArray([100, 50]), ByteArray([100, 51]), ByteArray([100, 52]), ByteArray([100, 53]), ByteArray([100, 54]), ByteArray([100, 55]), ByteArray([100, 56]), ByteArray([100, 57]), ByteArray([100, 97]), ByteArray([100, 98]), ByteArray([100, 99]), ByteArray([100, 100]), ByteArray([100, 101]), ByteArray([100, 102]), ByteArray([101, 48]), ByteArray([101, 49]), ByteArray([101, 50]), ByteArray([101, 51]), ByteArray([101, 52]), ByteArray([101, 53]), ByteArray([101, 54]), ByteArray([101, 55]), ByteArray([101, 56]), ByteArray([101, 57]), ByteArray([101, 97]), ByteArray([101, 98]), ByteArray([101, 99]), ByteArray([101, 100]), ByteArray([101, 101]), ByteArray([101, 102]), ByteArray([102, 48]), ByteArray([102, 49]), ByteArray([102, 50]), ByteArray([102, 51]), ByteArray([102, 52]), ByteArray([102, 53]), ByteArray([102, 54]), ByteArray([102, 55]), ByteArray([102, 56]), ByteArray([102, 57]), ByteArray([102, 97]), ByteArray([102, 98]), ByteArray([102, 99]), ByteArray([102, 100]), ByteArray([102, 101]), ByteArray([102, 102])];
-
- - - - - -## Function `encode` - -Encode -bytes in lowercase hex - - -

-public fun encode(bytes: vector<u8>): vector<u8>
-
- - - -
-Implementation - - -

-public fun encode(bytes: vector<u8>): vector<u8> \{
-    let (mut i, mut r, l) = (0, vector[], bytes.length());
-    let hex_vector = HEX;
-    while (i < l) \{
-        r.append(hex_vector[bytes[i] as u64]);
-        i = i + 1;
-    };
-    r
-}
-
- - - -
- - - -## Function `decode` - -Decode hex into -bytes -Takes a hex string (no 0x prefix) (e.g. b"0f3a") -Returns vector of -bytes that represents the hex string (e.g. x"0f3a") -Hex string can be case insensitive (e.g. b"0F3A" and b"0f3a" both return x"0f3a") -Aborts if the hex string does not have an even number of characters (as each hex character is 2 characters long) -Aborts if the hex string contains non-valid hex characters (valid characters are 0 - 9, a - f, A - F) - - -

-public fun decode(hex: vector<u8>): vector<u8>
-
- - - -
-Implementation - - -

-public fun decode(hex: vector<u8>): vector<u8> \{
-    let (mut i, mut r, l) = (0, vector[], hex.length());
-    assert!(l % 2 == 0, EInvalidHexLength);
-    while (i < l) \{
-        let decimal = decode_byte(hex[i]) * 16 + decode_byte(hex[i + 1]);
-        r.push_back(decimal);
-        i = i + 2;
-    };
-    r
-}
-
- - - -
- - - -## Function `decode_byte` - - - -

-fun decode_byte(hex: u8): u8
-
- - - -
-Implementation - - -

-fun decode_byte(hex: u8): u8 \{
-    if (/* 0 .. 9 */ 48 <= hex && hex < 58) \{
-        hex - 48
-    } else if (/* A .. F */ 65 <= hex && hex < 71) \{
-        10 + hex - 65
-    } else if (/* a .. f */ 97 <= hex && hex < 103) \{
-        10 + hex - 97
-    } else \{
-        abort ENotValidHexCharacter
-    }
-}
-
- - - -
diff --git a/crates/iota-framework/docs/iota-framework/hmac.mdx b/crates/iota-framework/docs/iota-framework/hmac.mdx deleted file mode 100644 index d277c933696..00000000000 --- a/crates/iota-framework/docs/iota-framework/hmac.mdx +++ /dev/null @@ -1,42 +0,0 @@ ---- -title: Module `0x2::hmac` ---- -import Link from '@docusaurus/Link'; - - - - -- [Function `hmac_sha3_256`](#0x2_hmac_hmac_sha3_256) - - -

-
- - - - - -## Function `hmac_sha3_256` - -@param key: HMAC key, arbitrary bytes. -@param msg: message to sign, arbitrary bytes. -Returns the 32 bytes digest of HMAC-SHA3-256(key, msg). - - -

-public fun hmac_sha3_256(key: &vector<u8>, msg: &vector<u8>): vector<u8>
-
- - - -
-Implementation - - -

-public native fun hmac_sha3_256(key: &vector<u8>, msg: &vector<u8>): vector<u8>;
-
- - - -
diff --git a/crates/iota-framework/docs/iota-framework/iota.mdx b/crates/iota-framework/docs/iota-framework/iota.mdx deleted file mode 100644 index ca455dba1be..00000000000 --- a/crates/iota-framework/docs/iota-framework/iota.mdx +++ /dev/null @@ -1,346 +0,0 @@ ---- -title: Module `0x2::iota` ---- -import Link from '@docusaurus/Link'; - - -`Coin` is the token used to pay for gas in IOTA. -It has 9 decimals, and the smallest unit (10^-9) is called "nano". - - -- [Struct `IOTA`](#0x2_iota_IOTA) -- [Struct `IotaTreasuryCap`](#0x2_iota_IotaTreasuryCap) -- [Constants](#@Constants_0) -- [Function `new`](#0x2_iota_new) -- [Function `transfer`](#0x2_iota_transfer) -- [Function `mint`](#0x2_iota_mint) -- [Function `mint_balance`](#0x2_iota_mint_balance) -- [Function `burn`](#0x2_iota_burn) -- [Function `burn_balance`](#0x2_iota_burn_balance) -- [Function `total_supply`](#0x2_iota_total_supply) - - -

-use 0x1::option;
-use 0x2::balance;
-use 0x2::coin;
-use 0x2::transfer;
-use 0x2::tx_context;
-use 0x2::url;
-
- - - - - -## Struct `IOTA` - -Name of the coin - - -

-struct IOTA has drop
-
- - - -
-Fields - - -
-
- -dummy_field: bool -
-
- -
-
- - -
- - - -## Struct `IotaTreasuryCap` - -The IOTA token treasury capability. -Protects the token from unauthorized changes. - - -

-struct IotaTreasuryCap has store
-
- - - -
-Fields - - -
-
- -inner: coin::TreasuryCap<iota::IOTA> -
-
- -
-
- - -
- - - -## Constants - - - - -Sender is not @0x0 the system address. - - -

-const ENotSystemAddress: u64 = 1;
-
- - - - - - - -

-const EAlreadyMinted: u64 = 0;
-
- - - - - -## Function `new` - -Register the -IOTA Coin to acquire -IotaTreasuryCap. -This should be called only once during genesis creation. - - -

-fun new(ctx: &mut tx_context::TxContext): iota::IotaTreasuryCap
-
- - - -
-Implementation - - -

-fun new(ctx: &mut TxContext): IotaTreasuryCap \{
-    assert!(ctx.sender() == @0x0, ENotSystemAddress);
-    assert!(ctx.epoch() == 0, EAlreadyMinted);
-
-    let (treasury, metadata) = coin::create_currency(
-        IOTA \{},
-        9,
-        b"IOTA",
-        b"IOTA",
-        b"The main (gas)token of the IOTA Network.",
-        option::some(url::new_unsafe_from_bytes(b"https://iota.org/logo.png")),
-        ctx
-    );
-
-    transfer::public_freeze_object(metadata);
-
-    IotaTreasuryCap \{
-        inner: treasury,
-    }
-}
-
- - - -
- - - -## Function `transfer` - - - -

-public entry fun transfer(c: coin::Coin<iota::IOTA>, recipient: address)
-
- - - -
-Implementation - - -

-public entry fun transfer(c: coin::Coin<IOTA>, recipient: address) \{
-    transfer::public_transfer(c, recipient)
-}
-
- - - -
- - - -## Function `mint` - -Create an IOTA coin worth -value and increase the total supply in -cap accordingly. - - -

-public fun mint(cap: &mut iota::IotaTreasuryCap, value: u64, ctx: &mut tx_context::TxContext): coin::Coin<iota::IOTA>
-
- - - -
-Implementation - - -

-public fun mint(cap: &mut IotaTreasuryCap, value: u64, ctx: &mut TxContext): Coin<IOTA> \{
-    assert!(ctx.sender() == @0x0, ENotSystemAddress);
-
-    cap.inner.mint(value, ctx)
-}
-
- - - -
- - - -## Function `mint_balance` - -Mint some amount of IOTA as a -Balance and increase the total supply in -cap accordingly. -Aborts if -value + -cap.inner.total_supply >= U64_MAX - - -

-public fun mint_balance(cap: &mut iota::IotaTreasuryCap, value: u64, ctx: &tx_context::TxContext): balance::Balance<iota::IOTA>
-
- - - -
-Implementation - - -

-public fun mint_balance(cap: &mut IotaTreasuryCap, value: u64, ctx: &TxContext): Balance<IOTA> \{
-    assert!(ctx.sender() == @0x0, ENotSystemAddress);
-
-    cap.inner.mint_balance(value)
-}
-
- - - -
- - - -## Function `burn` - -Destroy the IOTA coin -c and decrease the total supply in -cap accordingly. - - -

-public fun burn(cap: &mut iota::IotaTreasuryCap, c: coin::Coin<iota::IOTA>, ctx: &tx_context::TxContext): u64
-
- - - -
-Implementation - - -

-public fun burn(cap: &mut IotaTreasuryCap, c: Coin<IOTA>, ctx: &TxContext): u64 \{
-    assert!(ctx.sender() == @0x0, ENotSystemAddress);
-
-    cap.inner.burn(c)
-}
-
- - - -
- - - -## Function `burn_balance` - -Destroy the IOTA balance -b and decrease the total supply in -cap accordingly. - - -

-public fun burn_balance(cap: &mut iota::IotaTreasuryCap, b: balance::Balance<iota::IOTA>, ctx: &tx_context::TxContext): u64
-
- - - -
-Implementation - - -

-public fun burn_balance(cap: &mut IotaTreasuryCap, b: Balance<IOTA>, ctx: &TxContext): u64 \{
-    assert!(ctx.sender() == @0x0, ENotSystemAddress);
-
-    cap.inner.supply_mut().decrease_supply(b)
-}
-
- - - -
- - - -## Function `total_supply` - -Return the total number of IOTA's in circulation. - - -

-public fun total_supply(cap: &iota::IotaTreasuryCap): u64
-
- - - -
-Implementation - - -

-public fun total_supply(cap: &IotaTreasuryCap): u64 \{
-    cap.inner.total_supply()
-}
-
- - - -
diff --git a/crates/iota-framework/docs/iota-framework/kiosk.mdx b/crates/iota-framework/docs/iota-framework/kiosk.mdx deleted file mode 100644 index f1fb1cded90..00000000000 --- a/crates/iota-framework/docs/iota-framework/kiosk.mdx +++ /dev/null @@ -1,2240 +0,0 @@ ---- -title: Module `0x2::kiosk` ---- -import Link from '@docusaurus/Link'; - - -Kiosk is a primitive for building safe, decentralized and trustless trading -experiences. It allows storing and trading any types of assets as long as -the creator of these assets implements a -TransferPolicy for them. - - - - -#### Principles and philosophy: - - -- Kiosk provides guarantees of "true ownership"; - just like single owner -objects, assets stored in the Kiosk can only be managed by the Kiosk owner. -Only the owner can -place, -take, -list, perform any other actions on -assets in the Kiosk. - -- Kiosk aims to be generic - allowing for a small set of default behaviors -and not imposing any restrictions on how the assets can be traded. The only -default scenario is a -list + -purchase flow; any other trading logic can -be implemented on top using the -list_with_purchase_cap (and a matching - -purchase_with_cap) flow. - -- For every transaction happening with a third party a -TransferRequest is -created - this way creators are fully in control of the trading experience. - - - - -#### Asset states in the Kiosk: - - -- -placed - An asset is -placed into the Kiosk and can be -taken out by -the Kiosk owner; it's freely tradable and modifiable via the -borrow_mut -and -borrow_val functions. - -- -locked - Similar to -placed except that -take is disabled and the only -way to move the asset out of the Kiosk is to -list it or - -list_with_purchase_cap therefore performing a trade (isiotang a - -TransferRequest). The check on the -lock function makes sure that the - -TransferPolicy exists to not lock the item in a -Kiosk forever. - -- -listed - A -placed or a -locked item can be -listed for a fixed price -allowing anyone to -purchase it from the Kiosk. While listed, an item can -not be taken or modified. However, an immutable borrow via -borrow call is -still available. The -delist function returns the asset to the previous -state. - -- -listed_exclusively - An item is listed via the -list_with_purchase_cap -function (and a -PurchaseCap is created). While listed this way, an item -can not be -delist-ed unless a -PurchaseCap is returned. All actions -available at this item state require a -PurchaseCap: - -1. -purchase_with_cap - to purchase the item for a price equal or higher -than the -min_price set in the -PurchaseCap. -2. -return_purchase_cap - to return the -PurchaseCap and return the asset -into the previous state. - -When an item is listed exclusively it cannot be modified nor taken and -losing a -PurchaseCap would lock the item in the Kiosk forever. Therefore, -it is recommended to only use -PurchaseCap functionality in trusted -applications and not use it for direct trading (eg sending to another -account). - - - - -#### Using multiple Transfer Policies for different 'tracks': - - -Every -purchase or -purchase_with_purchase_cap creates a -TransferRequest -hot potato which must be resolved in a matching -TransferPolicy for the -transaction to pass. While the default scenario implies that there should be -a single -TransferPolicy<T> for -T; it is possible to have multiple, each -one having its own set of rules. - - - - -#### Examples: - - -- I create one -TransferPolicy with "Royalty Rule" for everyone -- I create a special -TransferPolicy for bearers of a "Club Membership" -object so they don't have to pay anything -- I create and wrap a -TransferPolicy so that players of my game can -transfer items between -Kiosks in game without any charge (and maybe not -even paying the price with a 0 IOTA PurchaseCap) - -``` -Kiosk -> (Item, TransferRequest) -... TransferRequest ------> Common Transfer Policy -... TransferRequest ------> In-game Wrapped Transfer Policy -... TransferRequest ------> Club Membership Transfer Policy -``` - -See -transfer_policy module for more details on how they function. - - - - [Principles and philosophy:](#@Principles_and_philosophy:_0) - - [Asset states in the Kiosk:](#@Asset_states_in_the_Kiosk:_1) - - [Using multiple Transfer Policies for different 'tracks':](#@Using_multiple_Transfer_Policies_for_different_'tracks':_2) - - [Examples:](#@Examples:_3) -- [Resource `Kiosk`](#0x2_kiosk_Kiosk) -- [Resource `KioskOwnerCap`](#0x2_kiosk_KioskOwnerCap) -- [Resource `PurchaseCap`](#0x2_kiosk_PurchaseCap) -- [Struct `Borrow`](#0x2_kiosk_Borrow) -- [Struct `Item`](#0x2_kiosk_Item) -- [Struct `Listing`](#0x2_kiosk_Listing) -- [Struct `Lock`](#0x2_kiosk_Lock) -- [Struct `ItemListed`](#0x2_kiosk_ItemListed) -- [Struct `ItemPurchased`](#0x2_kiosk_ItemPurchased) -- [Struct `ItemDelisted`](#0x2_kiosk_ItemDelisted) -- [Constants](#@Constants_4) -- [Function `default`](#0x2_kiosk_default) -- [Function `new`](#0x2_kiosk_new) -- [Function `close_and_withdraw`](#0x2_kiosk_close_and_withdraw) -- [Function `set_owner`](#0x2_kiosk_set_owner) -- [Function `set_owner_custom`](#0x2_kiosk_set_owner_custom) -- [Function `place`](#0x2_kiosk_place) -- [Function `lock`](#0x2_kiosk_lock) -- [Function `take`](#0x2_kiosk_take) -- [Function `list`](#0x2_kiosk_list) -- [Function `place_and_list`](#0x2_kiosk_place_and_list) -- [Function `delist`](#0x2_kiosk_delist) -- [Function `purchase`](#0x2_kiosk_purchase) -- [Function `list_with_purchase_cap`](#0x2_kiosk_list_with_purchase_cap) -- [Function `purchase_with_cap`](#0x2_kiosk_purchase_with_cap) -- [Function `return_purchase_cap`](#0x2_kiosk_return_purchase_cap) -- [Function `withdraw`](#0x2_kiosk_withdraw) -- [Function `lock_internal`](#0x2_kiosk_lock_internal) -- [Function `place_internal`](#0x2_kiosk_place_internal) -- [Function `uid_mut_internal`](#0x2_kiosk_uid_mut_internal) -- [Function `has_item`](#0x2_kiosk_has_item) -- [Function `has_item_with_type`](#0x2_kiosk_has_item_with_type) -- [Function `is_locked`](#0x2_kiosk_is_locked) -- [Function `is_listed`](#0x2_kiosk_is_listed) -- [Function `is_listed_exclusively`](#0x2_kiosk_is_listed_exclusively) -- [Function `has_access`](#0x2_kiosk_has_access) -- [Function `uid_mut_as_owner`](#0x2_kiosk_uid_mut_as_owner) -- [Function `set_allow_extensions`](#0x2_kiosk_set_allow_extensions) -- [Function `uid`](#0x2_kiosk_uid) -- [Function `uid_mut`](#0x2_kiosk_uid_mut) -- [Function `owner`](#0x2_kiosk_owner) -- [Function `item_count`](#0x2_kiosk_item_count) -- [Function `profits_amount`](#0x2_kiosk_profits_amount) -- [Function `profits_mut`](#0x2_kiosk_profits_mut) -- [Function `borrow`](#0x2_kiosk_borrow) -- [Function `borrow_mut`](#0x2_kiosk_borrow_mut) -- [Function `borrow_val`](#0x2_kiosk_borrow_val) -- [Function `return_val`](#0x2_kiosk_return_val) -- [Function `kiosk_owner_cap_for`](#0x2_kiosk_kiosk_owner_cap_for) -- [Function `purchase_cap_kiosk`](#0x2_kiosk_purchase_cap_kiosk) -- [Function `purchase_cap_item`](#0x2_kiosk_purchase_cap_item) -- [Function `purchase_cap_min_price`](#0x2_kiosk_purchase_cap_min_price) - - -

-use 0x1::option;
-use 0x2::balance;
-use 0x2::coin;
-use 0x2::dynamic_field;
-use 0x2::dynamic_object_field;
-use 0x2::event;
-use 0x2::iota;
-use 0x2::object;
-use 0x2::transfer;
-use 0x2::transfer_policy;
-use 0x2::tx_context;
-
- - - - - -## Resource `Kiosk` - -An object which allows selling collectibles within "kiosk" ecosystem. -By default gives the functionality to list an item openly - for anyone -to purchase providing the guarantees for creators that every transfer -needs to be approved via the -TransferPolicy. - - -

-struct Kiosk has store, key
-
- - - -
-Fields - - -
-
- -id: object::UID -
-
- -
-
- -profits: balance::Balance<iota::IOTA> -
-
- Balance of the Kiosk - all profits from sales go here. -
-
- -owner: address -
-
- Always point to -sender of the transaction. - Can be changed by calling -set_owner with Cap. -
-
- -item_count: u32 -
-
- Number of items stored in a Kiosk. Used to allow unpacking - an empty Kiosk if it was wrapped or has a single owner. -
-
- -allow_extensions: bool -
-
- [DEPRECATED] Please, don't use the -allow_extensions and the matching - -set_allow_extensions function - it is a legacy feature that is being - replaced by the -kiosk_extension module and its Extensions API. - - Exposes -uid_mut publicly when set to -true, set to -false by default. -
-
- - -
- - - -## Resource `KioskOwnerCap` - -A Capability granting the bearer a right to -place and -take items -from the -Kiosk as well as to -list them and -list_with_purchase_cap. - - -

-struct KioskOwnerCap has store, key
-
- - - -
-Fields - - -
-
- -id: object::UID -
-
- -
-
- -for: object::ID -
-
- -
-
- - -
- - - -## Resource `PurchaseCap` - -A capability which locks an item and gives a permission to -purchase it from a -Kiosk for any price no less than -min_price. - -Allows exclusive listing: only bearer of the -PurchaseCap can -purchase the asset. However, the capability should be used -carefully as losing it would lock the asset in the -Kiosk. - -The main application for the -PurchaseCap is building extensions -on top of the -Kiosk. - - -

-struct PurchaseCap<T: store, key> has store, key
-
- - - -
-Fields - - -
-
- -id: object::UID -
-
- -
-
- -kiosk_id: object::ID -
-
- ID of the -Kiosk the cap belongs to. -
-
- -item_id: object::ID -
-
- ID of the listed item. -
-
- -min_price: u64 -
-
- Minimum price for which the item can be purchased. -
-
- - -
- - - -## Struct `Borrow` - -Hot potato to ensure an item was returned after being taken using -the -borrow_val call. - - -

-struct Borrow
-
- - - -
-Fields - - -
-
- -kiosk_id: object::ID -
-
- -
-
- -item_id: object::ID -
-
- -
-
- - -
- - - -## Struct `Item` - -Dynamic field key for an item placed into the kiosk. - - -

-struct Item has copy, drop, store
-
- - - -
-Fields - - -
-
- -id: object::ID -
-
- -
-
- - -
- - - -## Struct `Listing` - -Dynamic field key for an active offer to purchase the T. If an -item is listed without a -PurchaseCap, exclusive is set to -false. - - -

-struct Listing has copy, drop, store
-
- - - -
-Fields - - -
-
- -id: object::ID -
-
- -
-
- -is_exclusive: bool -
-
- -
-
- - -
- - - -## Struct `Lock` - -Dynamic field key which marks that an item is locked in the -Kiosk and -can't be -taken. The item then can only be listed / sold via the PurchaseCap. -Lock is released on -purchase. - - -

-struct Lock has copy, drop, store
-
- - - -
-Fields - - -
-
- -id: object::ID -
-
- -
-
- - -
- - - -## Struct `ItemListed` - -Emitted when an item was listed by the safe owner. Can be used -to track available offers anywhere on the network; the event is -type-indexed which allows for searching for offers of a specific -T - - -

-struct ItemListed<T: store, key> has copy, drop
-
- - - -
-Fields - - -
-
- -kiosk: object::ID -
-
- -
-
- -id: object::ID -
-
- -
-
- -price: u64 -
-
- -
-
- - -
- - - -## Struct `ItemPurchased` - -Emitted when an item was purchased from the -Kiosk. Can be used -to track finalized sales across the network. The event is emitted -in both cases: when an item is purchased via the -PurchaseCap or -when it's purchased directly (via -list + -purchase). - -The -price is also emitted and might differ from the -price set -in the -ItemListed event. This is because the -PurchaseCap only -sets a minimum price for the item, and the actual price is defined -by the trading module / extension. - - -

-struct ItemPurchased<T: store, key> has copy, drop
-
- - - -
-Fields - - -
-
- -kiosk: object::ID -
-
- -
-
- -id: object::ID -
-
- -
-
- -price: u64 -
-
- -
-
- - -
- - - -## Struct `ItemDelisted` - -Emitted when an item was delisted by the safe owner. Can be used -to close tracked offers. - - -

-struct ItemDelisted<T: store, key> has copy, drop
-
- - - -
-Fields - - -
-
- -kiosk: object::ID -
-
- -
-
- -id: object::ID -
-
- -
-
- - -
- - - -## Constants - - - - -Trying to withdraw higher amount than stored. - - -

-const ENotEnough: u64 = 2;
-
- - - - - -Trying to withdraw profits and sender is not owner. - - -

-const ENotOwner: u64 = 0;
-
- - - - - -Trying to exclusively list an already listed item. - - -

-const EAlreadyListed: u64 = 6;
-
- - - - - -Coin paid does not match the offer price. - - -

-const EIncorrectAmount: u64 = 1;
-
- - - - - -Taking or mutably borrowing an item that is listed. - - -

-const EItemIsListed: u64 = 9;
-
- - - - - -Attempt to -take an item that is locked. - - -

-const EItemLocked: u64 = 8;
-
- - - - - -Item does not match -Borrow in -return_val. - - -

-const EItemMismatch: u64 = 10;
-
- - - - - -An is not found while trying to borrow. - - -

-const EItemNotFound: u64 = 11;
-
- - - - - -Attempt to take an item that has a -PurchaseCap issued. - - -

-const EListedExclusively: u64 = 4;
-
- - - - - -Trying to close a Kiosk and it has items in it. - - -

-const ENotEmpty: u64 = 3;
-
- - - - - -Delisting an item that is not listed. - - -

-const ENotListed: u64 = 12;
-
- - - - - -Trying to call -uid_mut when -allow_extensions set to false. - - -

-const EUidAccessNotAllowed: u64 = 7;
-
- - - - - - -PurchaseCap does not match the -Kiosk. - - -

-const EWrongKiosk: u64 = 5;
-
- - - - - -## Function `default` - -Creates a new Kiosk in a default configuration: sender receives the - -KioskOwnerCap and becomes the Owner, the -Kiosk is shared. - - -

-entry fun default(ctx: &mut tx_context::TxContext)
-
- - - -
-Implementation - - -

-entry fun default(ctx: &mut TxContext) \{
-    let (kiosk, cap) = new(ctx);
-    iota::transfer::transfer(cap, ctx.sender());
-    iota::transfer::share_object(kiosk);
-}
-
- - - -
- - - -## Function `new` - -Creates a new -Kiosk with a matching -KioskOwnerCap. - - -

-public fun new(ctx: &mut tx_context::TxContext): (kiosk::Kiosk, kiosk::KioskOwnerCap)
-
- - - -
-Implementation - - -

-public fun new(ctx: &mut TxContext): (Kiosk, KioskOwnerCap) \{
-    let kiosk = Kiosk \{
-        id: object::new(ctx),
-        profits: balance::zero(),
-        owner: ctx.sender(),
-        item_count: 0,
-        allow_extensions: false
-    };
-
-    let cap = KioskOwnerCap \{
-        id: object::new(ctx),
-        `for`: object::id(&kiosk)
-    };
-
-    (kiosk, cap)
-}
-
- - - -
- - - -## Function `close_and_withdraw` - -Unpacks and destroys a Kiosk returning the profits (even if "0"). -Can only be performed by the bearer of the -KioskOwnerCap in the -case where there's no items inside and a -Kiosk is not shared. - - -

-public fun close_and_withdraw(self: kiosk::Kiosk, cap: kiosk::KioskOwnerCap, ctx: &mut tx_context::TxContext): coin::Coin<iota::IOTA>
-
- - - -
-Implementation - - -

-public fun close_and_withdraw(
-    self: Kiosk, cap: KioskOwnerCap, ctx: &mut TxContext
-): Coin<IOTA> \{
-    let Kiosk \{ id, profits, owner: _, item_count, allow_extensions: _ } = self;
-    let KioskOwnerCap \{ id: cap_id, `for` } = cap;
-
-    assert!(id.to_inner() == `for`, ENotOwner);
-    assert!(item_count == 0, ENotEmpty);
-
-    cap_id.delete();
-    id.delete();
-
-    profits.into_coin(ctx)
-}
-
- - - -
- - - -## Function `set_owner` - -Change the -owner field to the transaction sender. -The change is purely cosmetical and does not affect any of the -basic kiosk functions unless some logic for this is implemented -in a third party module. - - -

-public fun set_owner(self: &mut kiosk::Kiosk, cap: &kiosk::KioskOwnerCap, ctx: &tx_context::TxContext)
-
- - - -
-Implementation - - -

-public fun set_owner(
-    self: &mut Kiosk, cap: &KioskOwnerCap, ctx: &TxContext
-) \{
-    assert!(self.has_access(cap), ENotOwner);
-    self.owner = ctx.sender();
-}
-
- - - -
- - - -## Function `set_owner_custom` - -Update the -owner field with a custom address. Can be used for -implementing a custom logic that relies on the -Kiosk owner. - - -

-public fun set_owner_custom(self: &mut kiosk::Kiosk, cap: &kiosk::KioskOwnerCap, owner: address)
-
- - - -
-Implementation - - -

-public fun set_owner_custom(
-    self: &mut Kiosk, cap: &KioskOwnerCap, owner: address
-) \{
-    assert!(self.has_access(cap), ENotOwner);
-    self.owner = owner
-}
-
- - - -
- - - -## Function `place` - -Place any object into a Kiosk. -Performs an authorization check to make sure only owner can do that. - - -

-public fun place<T: store, key>(self: &mut kiosk::Kiosk, cap: &kiosk::KioskOwnerCap, item: T)
-
- - - -
-Implementation - - -

-public fun place<T: key + store>(
-    self: &mut Kiosk, cap: &KioskOwnerCap, item: T
-) \{
-    assert!(self.has_access(cap), ENotOwner);
-    self.place_internal(item)
-}
-
- - - -
- - - -## Function `lock` - -Place an item to the -Kiosk and issue a -Lock for it. Once placed this -way, an item can only be listed either with a -list function or with a - -list_with_purchase_cap. - -Requires policy for -T to make sure that there's an issued -TransferPolicy -and the item can be sold, otherwise the asset might be locked forever. - - -

-public fun lock<T: store, key>(self: &mut kiosk::Kiosk, cap: &kiosk::KioskOwnerCap, _policy: &transfer_policy::TransferPolicy<T>, item: T)
-
- - - -
-Implementation - - -

-public fun lock<T: key + store>(
-    self: &mut Kiosk, cap: &KioskOwnerCap, _policy: &TransferPolicy<T>, item: T
-) \{
-    assert!(self.has_access(cap), ENotOwner);
-    self.lock_internal(item)
-}
-
- - - -
- - - -## Function `take` - -Take any object from the Kiosk. -Performs an authorization check to make sure only owner can do that. - - -

-public fun take<T: store, key>(self: &mut kiosk::Kiosk, cap: &kiosk::KioskOwnerCap, id: object::ID): T
-
- - - -
-Implementation - - -

-public fun take<T: key + store>(
-    self: &mut Kiosk, cap: &KioskOwnerCap, id: ID
-): T \{
-    assert!(self.has_access(cap), ENotOwner);
-    assert!(!self.is_locked(id), EItemLocked);
-    assert!(!self.is_listed_exclusively(id), EListedExclusively);
-    assert!(self.has_item(id), EItemNotFound);
-
-    self.item_count = self.item_count - 1;
-    df::remove_if_exists<Listing, u64>(&mut self.id, Listing \{ id, is_exclusive: false });
-    dof::remove(&mut self.id, Item \{ id })
-}
-
- - - -
- - - -## Function `list` - -List the item by setting a price and making it available for purchase. -Performs an authorization check to make sure only owner can sell. - - -

-public fun list<T: store, key>(self: &mut kiosk::Kiosk, cap: &kiosk::KioskOwnerCap, id: object::ID, price: u64)
-
- - - -
-Implementation - - -

-public fun list<T: key + store>(
-    self: &mut Kiosk, cap: &KioskOwnerCap, id: ID, price: u64
-) \{
-    assert!(self.has_access(cap), ENotOwner);
-    assert!(self.has_item_with_type<T>(id), EItemNotFound);
-    assert!(!self.is_listed_exclusively(id), EListedExclusively);
-
-    df::add(&mut self.id, Listing \{ id, is_exclusive: false }, price);
-    event::emit(ItemListed<T> \{ kiosk: object::id(self), id, price })
-}
-
- - - -
- - - -## Function `place_and_list` - -Calls -place and -list together - simplifies the flow. - - -

-public fun place_and_list<T: store, key>(self: &mut kiosk::Kiosk, cap: &kiosk::KioskOwnerCap, item: T, price: u64)
-
- - - -
-Implementation - - -

-public fun place_and_list<T: key + store>(
-    self: &mut Kiosk, cap: &KioskOwnerCap, item: T, price: u64
-) \{
-    let id = object::id(&item);
-    self.place(cap, item);
-    self.list<T>(cap, id, price)
-}
-
- - - -
- - - -## Function `delist` - -Remove an existing listing from the -Kiosk and keep the item in the -user Kiosk. Can only be performed by the owner of the -Kiosk. - - -

-public fun delist<T: store, key>(self: &mut kiosk::Kiosk, cap: &kiosk::KioskOwnerCap, id: object::ID)
-
- - - -
-Implementation - - -

-public fun delist<T: key + store>(
-    self: &mut Kiosk, cap: &KioskOwnerCap, id: ID
-) \{
-    assert!(self.has_access(cap), ENotOwner);
-    assert!(self.has_item_with_type<T>(id), EItemNotFound);
-    assert!(!self.is_listed_exclusively(id), EListedExclusively);
-    assert!(self.is_listed(id), ENotListed);
-
-    df::remove<Listing, u64>(&mut self.id, Listing \{ id, is_exclusive: false });
-    event::emit(ItemDelisted<T> \{ kiosk: object::id(self), id })
-}
-
- - - -
- - - -## Function `purchase` - -Make a trade: pay the owner of the item and request a Transfer to the -target -kiosk (to prevent item being taken by the approving party). - -Received -TransferRequest needs to be handled by the publisher of the T, -if they have a method implemented that allows a trade, it is possible to -request their approval (by calling some function) so that the trade can be -finalized. - - -

-public fun purchase<T: store, key>(self: &mut kiosk::Kiosk, id: object::ID, payment: coin::Coin<iota::IOTA>): (T, transfer_policy::TransferRequest<T>)
-
- - - -
-Implementation - - -

-public fun purchase<T: key + store>(
-    self: &mut Kiosk, id: ID, payment: Coin<IOTA>
-): (T, TransferRequest<T>) \{
-    let price = df::remove<Listing, u64>(&mut self.id, Listing \{ id, is_exclusive: false });
-    let inner = dof::remove<Item, T>(&mut self.id, Item \{ id });
-
-    self.item_count = self.item_count - 1;
-    assert!(price == payment.value(), EIncorrectAmount);
-    df::remove_if_exists<Lock, bool>(&mut self.id, Lock \{ id });
-    coin::put(&mut self.profits, payment);
-
-    event::emit(ItemPurchased<T> \{ kiosk: object::id(self), id, price });
-
-    (inner, transfer_policy::new_request(id, price, object::id(self)))
-}
-
- - - -
- - - -## Function `list_with_purchase_cap` - -Creates a -PurchaseCap which gives the right to purchase an item -for any price equal or higher than the -min_price. - - -

-public fun list_with_purchase_cap<T: store, key>(self: &mut kiosk::Kiosk, cap: &kiosk::KioskOwnerCap, id: object::ID, min_price: u64, ctx: &mut tx_context::TxContext): kiosk::PurchaseCap<T>
-
- - - -
-Implementation - - -

-public fun list_with_purchase_cap<T: key + store>(
-    self: &mut Kiosk, cap: &KioskOwnerCap, id: ID, min_price: u64, ctx: &mut TxContext
-): PurchaseCap<T> \{
-    assert!(self.has_access(cap), ENotOwner);
-    assert!(self.has_item_with_type<T>(id), EItemNotFound);
-    assert!(!self.is_listed(id), EAlreadyListed);
-
-    df::add(&mut self.id, Listing \{ id, is_exclusive: true }, min_price);
-
-    PurchaseCap<T> \{
-        min_price,
-        item_id: id,
-        id: object::new(ctx),
-        kiosk_id: object::id(self),
-    }
-}
-
- - - -
- - - -## Function `purchase_with_cap` - -Unpack the -PurchaseCap and call -purchase. Sets the payment amount -as the price for the listing making sure it's no less than -min_amount. - - -

-public fun purchase_with_cap<T: store, key>(self: &mut kiosk::Kiosk, purchase_cap: kiosk::PurchaseCap<T>, payment: coin::Coin<iota::IOTA>): (T, transfer_policy::TransferRequest<T>)
-
- - - -
-Implementation - - -

-public fun purchase_with_cap<T: key + store>(
-    self: &mut Kiosk, purchase_cap: PurchaseCap<T>, payment: Coin<IOTA>
-): (T, TransferRequest<T>) \{
-    let PurchaseCap \{ id, item_id, kiosk_id, min_price } = purchase_cap;
-    id.delete();
-
-    let id = item_id;
-    let paid = payment.value();
-    assert!(paid >= min_price, EIncorrectAmount);
-    assert!(object::id(self) == kiosk_id, EWrongKiosk);
-
-    df::remove<Listing, u64>(&mut self.id, Listing \{ id, is_exclusive: true });
-
-    coin::put(&mut self.profits, payment);
-    self.item_count = self.item_count - 1;
-    df::remove_if_exists<Lock, bool>(&mut self.id, Lock \{ id });
-    let item = dof::remove<Item, T>(&mut self.id, Item \{ id });
-
-    (item, transfer_policy::new_request(id, paid, object::id(self)))
-}
-
- - - -
- - - -## Function `return_purchase_cap` - -Return the -PurchaseCap without making a purchase; remove an active offer and -allow the item for taking. Can only be returned to its -Kiosk, aborts otherwise. - - -

-public fun return_purchase_cap<T: store, key>(self: &mut kiosk::Kiosk, purchase_cap: kiosk::PurchaseCap<T>)
-
- - - -
-Implementation - - -

-public fun return_purchase_cap<T: key + store>(
-    self: &mut Kiosk, purchase_cap: PurchaseCap<T>
-) \{
-    let PurchaseCap \{ id, item_id, kiosk_id, min_price: _ } = purchase_cap;
-
-    assert!(object::id(self) == kiosk_id, EWrongKiosk);
-    df::remove<Listing, u64>(&mut self.id, Listing \{ id: item_id, is_exclusive: true });
-    id.delete()
-}
-
- - - -
- - - -## Function `withdraw` - -Withdraw profits from the Kiosk. - - -

-public fun withdraw(self: &mut kiosk::Kiosk, cap: &kiosk::KioskOwnerCap, amount: option::Option<u64>, ctx: &mut tx_context::TxContext): coin::Coin<iota::IOTA>
-
- - - -
-Implementation - - -

-public fun withdraw(
-    self: &mut Kiosk, cap: &KioskOwnerCap, amount: Option<u64>, ctx: &mut TxContext
-): Coin<IOTA> \{
-    assert!(self.has_access(cap), ENotOwner);
-
-    let amount = if (amount.is_some()) \{
-        let amt = amount.destroy_some();
-        assert!(amt <= self.profits.value(), ENotEnough);
-        amt
-    } else \{
-        self.profits.value()
-    };
-
-    coin::take(&mut self.profits, amount, ctx)
-}
-
- - - -
- - - -## Function `lock_internal` - -Internal: "lock" an item disabling the -take action. - - -

-public(friend) fun lock_internal<T: store, key>(self: &mut kiosk::Kiosk, item: T)
-
- - - -
-Implementation - - -

-public(package) fun lock_internal<T: key + store>(self: &mut Kiosk, item: T) \{
-    df::add(&mut self.id, Lock \{ id: object::id(&item) }, true);
-    self.place_internal(item)
-}
-
- - - -
- - - -## Function `place_internal` - -Internal: "place" an item to the Kiosk and increment the item count. - - -

-public(friend) fun place_internal<T: store, key>(self: &mut kiosk::Kiosk, item: T)
-
- - - -
-Implementation - - -

-public(package) fun place_internal<T: key + store>(self: &mut Kiosk, item: T) \{
-    self.item_count = self.item_count + 1;
-    dof::add(&mut self.id, Item \{ id: object::id(&item) }, item)
-}
-
- - - -
- - - -## Function `uid_mut_internal` - -Internal: get a mutable access to the UID. - - -

-public(friend) fun uid_mut_internal(self: &mut kiosk::Kiosk): &mut object::UID
-
- - - -
-Implementation - - -

-public(package) fun uid_mut_internal(self: &mut Kiosk): &mut UID \{
-    &mut self.id
-}
-
- - - -
- - - -## Function `has_item` - -Check whether the -item is present in the -Kiosk. - - -

-public fun has_item(self: &kiosk::Kiosk, id: object::ID): bool
-
- - - -
-Implementation - - -

-public fun has_item(self: &Kiosk, id: ID): bool \{
-    dof::exists_(&self.id, Item \{ id })
-}
-
- - - -
- - - -## Function `has_item_with_type` - -Check whether the -item is present in the -Kiosk and has type T. - - -

-public fun has_item_with_type<T: store, key>(self: &kiosk::Kiosk, id: object::ID): bool
-
- - - -
-Implementation - - -

-public fun has_item_with_type<T: key + store>(self: &Kiosk, id: ID): bool \{
-    dof::exists_with_type<Item, T>(&self.id, Item \{ id })
-}
-
- - - -
- - - -## Function `is_locked` - -Check whether an item with the -id is locked in the -Kiosk. Meaning -that the only two actions that can be performed on it are -list and - -list_with_purchase_cap, it cannot be -taken out of the -Kiosk. - - -

-public fun is_locked(self: &kiosk::Kiosk, id: object::ID): bool
-
- - - -
-Implementation - - -

-public fun is_locked(self: &Kiosk, id: ID): bool \{
-    df::exists_(&self.id, Lock \{ id })
-}
-
- - - -
- - - -## Function `is_listed` - -Check whether an -item is listed (exclusively or non exclusively). - - -

-public fun is_listed(self: &kiosk::Kiosk, id: object::ID): bool
-
- - - -
-Implementation - - -

-public fun is_listed(self: &Kiosk, id: ID): bool \{
-    df::exists_(&self.id, Listing \{ id, is_exclusive: false })
-    || self.is_listed_exclusively(id)
-}
-
- - - -
- - - -## Function `is_listed_exclusively` - -Check whether there's a -PurchaseCap issued for an item. - - -

-public fun is_listed_exclusively(self: &kiosk::Kiosk, id: object::ID): bool
-
- - - -
-Implementation - - -

-public fun is_listed_exclusively(self: &Kiosk, id: ID): bool \{
-    df::exists_(&self.id, Listing \{ id, is_exclusive: true })
-}
-
- - - -
- - - -## Function `has_access` - -Check whether the -KioskOwnerCap matches the -Kiosk. - - -

-public fun has_access(self: &mut kiosk::Kiosk, cap: &kiosk::KioskOwnerCap): bool
-
- - - -
-Implementation - - -

-public fun has_access(self: &mut Kiosk, cap: &KioskOwnerCap): bool \{
-    object::id(self) == cap.`for`
-}
-
- - - -
- - - -## Function `uid_mut_as_owner` - -Access the -UID using the -KioskOwnerCap. - - -

-public fun uid_mut_as_owner(self: &mut kiosk::Kiosk, cap: &kiosk::KioskOwnerCap): &mut object::UID
-
- - - -
-Implementation - - -

-public fun uid_mut_as_owner(
-    self: &mut Kiosk, cap: &KioskOwnerCap
-): &mut UID \{
-    assert!(self.has_access(cap), ENotOwner);
-    &mut self.id
-}
-
- - - -
- - - -## Function `set_allow_extensions` - -[DEPRECATED] -Allow or disallow -uid and -uid_mut access via the -allow_extensions -setting. - - -

-public fun set_allow_extensions(self: &mut kiosk::Kiosk, cap: &kiosk::KioskOwnerCap, allow_extensions: bool)
-
- - - -
-Implementation - - -

-public fun set_allow_extensions(
-    self: &mut Kiosk, cap: &KioskOwnerCap, allow_extensions: bool
-) \{
-    assert!(self.has_access(cap), ENotOwner);
-    self.allow_extensions = allow_extensions;
-}
-
- - - -
- - - -## Function `uid` - -Get the immutable -UID for dynamic field access. -Always enabled. - -Given the &UID can be used for reading keys and authorization, -its access - - -

-public fun uid(self: &kiosk::Kiosk): &object::UID
-
- - - -
-Implementation - - -

-public fun uid(self: &Kiosk): &UID \{
-    &self.id
-}
-
- - - -
- - - -## Function `uid_mut` - -Get the mutable -UID for dynamic field access and extensions. -Aborts if -allow_extensions set to -false. - - -

-public fun uid_mut(self: &mut kiosk::Kiosk): &mut object::UID
-
- - - -
-Implementation - - -

-public fun uid_mut(self: &mut Kiosk): &mut UID \{
-    assert!(self.allow_extensions, EUidAccessNotAllowed);
-    &mut self.id
-}
-
- - - -
- - - -## Function `owner` - -Get the owner of the Kiosk. - - -

-public fun owner(self: &kiosk::Kiosk): address
-
- - - -
-Implementation - - -

-public fun owner(self: &Kiosk): address \{
-    self.owner
-}
-
- - - -
- - - -## Function `item_count` - -Get the number of items stored in a Kiosk. - - -

-public fun item_count(self: &kiosk::Kiosk): u32
-
- - - -
-Implementation - - -

-public fun item_count(self: &Kiosk): u32 \{
-    self.item_count
-}
-
- - - -
- - - -## Function `profits_amount` - -Get the amount of profits collected by selling items. - - -

-public fun profits_amount(self: &kiosk::Kiosk): u64
-
- - - -
-Implementation - - -

-public fun profits_amount(self: &Kiosk): u64 \{
-    self.profits.value()
-}
-
- - - -
- - - -## Function `profits_mut` - -Get mutable access to -profits - owner only action. - - -

-public fun profits_mut(self: &mut kiosk::Kiosk, cap: &kiosk::KioskOwnerCap): &mut balance::Balance<iota::IOTA>
-
- - - -
-Implementation - - -

-public fun profits_mut(self: &mut Kiosk, cap: &KioskOwnerCap): &mut Balance<IOTA> \{
-    assert!(self.has_access(cap), ENotOwner);
-    &mut self.profits
-}
-
- - - -
- - - -## Function `borrow` - -Immutably borrow an item from the -Kiosk. Any item can be -borrowed -at any time. - - -

-public fun borrow<T: store, key>(self: &kiosk::Kiosk, cap: &kiosk::KioskOwnerCap, id: object::ID): &T
-
- - - -
-Implementation - - -

-public fun borrow<T: key + store>(
-    self: &Kiosk, cap: &KioskOwnerCap, id: ID
-): &T \{
-    assert!(object::id(self) == cap.`for`, ENotOwner);
-    assert!(self.has_item(id), EItemNotFound);
-
-    dof::borrow(&self.id, Item \{ id })
-}
-
- - - -
- - - -## Function `borrow_mut` - -Mutably borrow an item from the -Kiosk. -Item can be -borrow_muted only if it's not -is_listed. - - -

-public fun borrow_mut<T: store, key>(self: &mut kiosk::Kiosk, cap: &kiosk::KioskOwnerCap, id: object::ID): &mut T
-
- - - -
-Implementation - - -

-public fun borrow_mut<T: key + store>(
-    self: &mut Kiosk, cap: &KioskOwnerCap, id: ID
-): &mut T \{
-    assert!(self.has_access(cap), ENotOwner);
-    assert!(self.has_item(id), EItemNotFound);
-    assert!(!self.is_listed(id), EItemIsListed);
-
-    dof::borrow_mut(&mut self.id, Item \{ id })
-}
-
- - - -
- - - -## Function `borrow_val` - -Take the item from the -Kiosk with a guarantee that it will be returned. -Item can be -borrow_val-ed only if it's not -is_listed. - - -

-public fun borrow_val<T: store, key>(self: &mut kiosk::Kiosk, cap: &kiosk::KioskOwnerCap, id: object::ID): (T, kiosk::Borrow)
-
- - - -
-Implementation - - -

-public fun borrow_val<T: key + store>(
-    self: &mut Kiosk, cap: &KioskOwnerCap, id: ID
-): (T, Borrow) \{
-    assert!(self.has_access(cap), ENotOwner);
-    assert!(self.has_item(id), EItemNotFound);
-    assert!(!self.is_listed(id), EItemIsListed);
-
-    (
-        dof::remove(&mut self.id, Item \{ id }),
-        Borrow \{ kiosk_id: object::id(self), item_id: id }
-    )
-}
-
- - - -
- - - -## Function `return_val` - -Return the borrowed item to the -Kiosk. This method cannot be avoided -if -borrow_val is used. - - -

-public fun return_val<T: store, key>(self: &mut kiosk::Kiosk, item: T, borrow: kiosk::Borrow)
-
- - - -
-Implementation - - -

-public fun return_val<T: key + store>(
-    self: &mut Kiosk, item: T, borrow: Borrow
-) \{
-    let Borrow \{ kiosk_id, item_id } = borrow;
-
-    assert!(object::id(self) == kiosk_id, EWrongKiosk);
-    assert!(object::id(&item) == item_id, EItemMismatch);
-
-    dof::add(&mut self.id, Item \{ id: item_id }, item);
-}
-
- - - -
- - - -## Function `kiosk_owner_cap_for` - -Get the -for field of the -KioskOwnerCap. - - -

-public fun kiosk_owner_cap_for(cap: &kiosk::KioskOwnerCap): object::ID
-
- - - -
-Implementation - - -

-public fun kiosk_owner_cap_for(cap: &KioskOwnerCap): ID \{
-    cap.`for`
-}
-
- - - -
- - - -## Function `purchase_cap_kiosk` - -Get the -kiosk_id from the -PurchaseCap. - - -

-public fun purchase_cap_kiosk<T: store, key>(self: &kiosk::PurchaseCap<T>): object::ID
-
- - - -
-Implementation - - -

-public fun purchase_cap_kiosk<T: key + store>(self: &PurchaseCap<T>): ID \{
-    self.kiosk_id
-}
-
- - - -
- - - -## Function `purchase_cap_item` - -Get the -Item_id from the -PurchaseCap. - - -

-public fun purchase_cap_item<T: store, key>(self: &kiosk::PurchaseCap<T>): object::ID
-
- - - -
-Implementation - - -

-public fun purchase_cap_item<T: key + store>(self: &PurchaseCap<T>): ID \{
-    self.item_id
-}
-
- - - -
- - - -## Function `purchase_cap_min_price` - -Get the -min_price from the -PurchaseCap. - - -

-public fun purchase_cap_min_price<T: store, key>(self: &kiosk::PurchaseCap<T>): u64
-
- - - -
-Implementation - - -

-public fun purchase_cap_min_price<T: key + store>(self: &PurchaseCap<T>): u64 \{
-    self.min_price
-}
-
- - - -
diff --git a/crates/iota-framework/docs/iota-framework/kiosk_extension.mdx b/crates/iota-framework/docs/iota-framework/kiosk_extension.mdx deleted file mode 100644 index 434860df20d..00000000000 --- a/crates/iota-framework/docs/iota-framework/kiosk_extension.mdx +++ /dev/null @@ -1,752 +0,0 @@ ---- -title: Module `0x2::kiosk_extension` ---- -import Link from '@docusaurus/Link'; - - -This module implements the Kiosk Extensions functionality. It allows -exposing previously protected (only-owner) methods to third-party apps. - -A Kiosk Extension is a module that implements any functionality on top of -the -Kiosk without discarding nor blocking the base. Given that -Kiosk -itself is a trading primitive, most of the extensions are expected to be -related to trading. However, there's no limit to what can be built using the - -kiosk_extension module, as it gives certain benefits such as using -Kiosk -as the storage for any type of data / assets. - - - - -#### Flow: - -- An extension can only be installed by the Kiosk Owner and requires an -authorization via the -KioskOwnerCap. -- When installed, the extension is given a permission bitmap that allows it -to perform certain protected actions (eg -place, -lock). However, it is -possible to install an extension that does not have any permissions. -- Kiosk Owner can -disable the extension at any time, which prevents it -from performing any protected actions. The storage is still available to the -extension until it is completely removed. -- A disabled extension can be -enabled at any time giving the permissions -back to the extension. -- An extension permissions follow the all-or-nothing policy. Either all of -the requested permissions are granted or none of them (can't install). - - - - -#### Examples: - -- An Auction extension can utilize the storage to store Auction-related data -while utilizing the same -Kiosk object that the items are stored in. -- A Marketplace extension that implements custom events and fees for the -default trading functionality. - - - - -#### Notes: - -- Trading functionality can utilize the -PurchaseCap to build a custom -logic around the purchase flow. However, it should be carefully managed to -prevent asset locking. -- -kiosk_extension is a friend module to -kiosk and has access to its -internal functions (such as -place_internal and -lock_internal to -implement custom authorization scheme for -place and -lock respectively). - - - - [Flow:](#@Flow:_0) - - [Examples:](#@Examples:_1) - - [Notes:](#@Notes:_2) -- [Struct `Extension`](#0x2_kiosk_extension_Extension) -- [Struct `ExtensionKey`](#0x2_kiosk_extension_ExtensionKey) -- [Constants](#@Constants_3) -- [Function `add`](#0x2_kiosk_extension_add) -- [Function `disable`](#0x2_kiosk_extension_disable) -- [Function `enable`](#0x2_kiosk_extension_enable) -- [Function `remove`](#0x2_kiosk_extension_remove) -- [Function `storage`](#0x2_kiosk_extension_storage) -- [Function `storage_mut`](#0x2_kiosk_extension_storage_mut) -- [Function `place`](#0x2_kiosk_extension_place) -- [Function `lock`](#0x2_kiosk_extension_lock) -- [Function `is_installed`](#0x2_kiosk_extension_is_installed) -- [Function `is_enabled`](#0x2_kiosk_extension_is_enabled) -- [Function `can_place`](#0x2_kiosk_extension_can_place) -- [Function `can_lock`](#0x2_kiosk_extension_can_lock) -- [Function `extension`](#0x2_kiosk_extension_extension) -- [Function `extension_mut`](#0x2_kiosk_extension_extension_mut) - - -

-use 0x2::bag;
-use 0x2::dynamic_field;
-use 0x2::kiosk;
-use 0x2::object;
-use 0x2::transfer_policy;
-use 0x2::tx_context;
-
- - - - - -## Struct `Extension` - -The Extension struct contains the data used by the extension and the -configuration for this extension. Stored under the -ExtensionKey -dynamic field. - - -

-struct Extension has store
-
- - - -
-Fields - - -
-
- -storage: bag::Bag -
-
- Storage for the extension, an isolated Bag. By putting the extension - into a single dynamic field, we reduce the amount of fields on the - top level (eg items / listings) while giving extension developers - the ability to store any data they want. -
-
- -permissions: u128 -
-
- Bitmap of permissions that the extension has (can be revoked any - moment). It's all or nothing policy - either the extension has the - required permissions or no permissions at all. - - 1st bit - -place - allows to place items for sale - 2nd bit - -lock and -place - allows to lock items (and place) - - For example: - - -10 - allows to place items and lock them. - - -11 - allows to place items and lock them ( -lock includes -place). - - -01 - allows to place items, but not lock them. - - -00 - no permissions. -
-
- -is_enabled: bool -
-
- Whether the extension can call protected actions. By default, all - extensions are enabled (on -add call), however the Kiosk - owner can disable them at any time. - - Disabling the extension does not limit its access to the storage. -
-
- - -
- - - -## Struct `ExtensionKey` - -The -ExtensionKey is a typed dynamic field key used to store the -extension configuration and data. -Ext is a phantom type that is used -to identify the extension witness. - - -

-struct ExtensionKey<Ext> has copy, drop, store
-
- - - -
-Fields - - -
-
- -dummy_field: bool -
-
- -
-
- - -
- - - -## Constants - - - - -Trying to add an extension while not being the owner of the Kiosk. - - -

-const ENotOwner: u64 = 0;
-
- - - - - -Extension is trying to access a permissioned action while not having -the required permission. - - -

-const EExtensionNotAllowed: u64 = 2;
-
- - - - - -Extension is not installed in the Kiosk. - - -

-const EExtensionNotInstalled: u64 = 3;
-
- - - - - -Value that represents the -lock and -place permission in the -permissions bitmap. - - -

-const LOCK: u128 = 2;
-
- - - - - -Value that represents the -place permission in the permissions bitmap. - - -

-const PLACE: u128 = 1;
-
- - - - - -## Function `add` - -Add an extension to the Kiosk. Can only be performed by the owner. The -extension witness is required to allow extensions define their set of -permissions in the custom -add call. - - -

-public fun add<Ext: drop>(_ext: Ext, self: &mut kiosk::Kiosk, cap: &kiosk::KioskOwnerCap, permissions: u128, ctx: &mut tx_context::TxContext)
-
- - - -
-Implementation - - -

-public fun add<Ext: drop>(
-    _ext: Ext,
-    self: &mut Kiosk,
-    cap: &KioskOwnerCap,
-    permissions: u128,
-    ctx: &mut TxContext
-) \{
-    assert!(self.has_access(cap), ENotOwner);
-    df::add(
-        self.uid_mut_as_owner(cap),
-        ExtensionKey<Ext> \{},
-        Extension \{
-            storage: bag::new(ctx),
-            permissions,
-            is_enabled: true,
-        }
-    )
-}
-
- - - -
- - - -## Function `disable` - -Revoke permissions from the extension. While it does not remove the -extension completely, it keeps it from performing any protected actions. -The storage is still available to the extension (until it's removed). - - -

-public fun disable<Ext: drop>(self: &mut kiosk::Kiosk, cap: &kiosk::KioskOwnerCap)
-
- - - -
-Implementation - - -

-public fun disable<Ext: drop>(
-    self: &mut Kiosk,
-    cap: &KioskOwnerCap,
-) \{
-    assert!(self.has_access(cap), ENotOwner);
-    assert!(is_installed<Ext>(self), EExtensionNotInstalled);
-    extension_mut<Ext>(self).is_enabled = false;
-}
-
- - - -
- - - -## Function `enable` - -Re-enable the extension allowing it to call protected actions (eg - -place, -lock). By default, all added extensions are enabled. Kiosk -owner can disable them via -disable call. - - -

-public fun enable<Ext: drop>(self: &mut kiosk::Kiosk, cap: &kiosk::KioskOwnerCap)
-
- - - -
-Implementation - - -

-public fun enable<Ext: drop>(
-    self: &mut Kiosk,
-    cap: &KioskOwnerCap,
-) \{
-    assert!(self.has_access(cap), ENotOwner);
-    assert!(is_installed<Ext>(self), EExtensionNotInstalled);
-    extension_mut<Ext>(self).is_enabled = true;
-}
-
- - - -
- - - -## Function `remove` - -Remove an extension from the Kiosk. Can only be performed by the owner, -the extension storage must be empty for the transaction to succeed. - - -

-public fun remove<Ext: drop>(self: &mut kiosk::Kiosk, cap: &kiosk::KioskOwnerCap)
-
- - - -
-Implementation - - -

-public fun remove<Ext: drop>(
-    self: &mut Kiosk, cap: &KioskOwnerCap
-) \{
-    assert!(self.has_access(cap), ENotOwner);
-    assert!(is_installed<Ext>(self), EExtensionNotInstalled);
-
-    let Extension \{
-        storage,
-        permissions: _,
-        is_enabled: _,
-    } = df::remove(self.uid_mut_as_owner(cap), ExtensionKey<Ext> \{});
-
-    storage.destroy_empty();
-}
-
- - - -
- - - -## Function `storage` - -Get immutable access to the extension storage. Can only be performed by -the extension as long as the extension is installed. - - -

-public fun storage<Ext: drop>(_ext: Ext, self: &kiosk::Kiosk): &bag::Bag
-
- - - -
-Implementation - - -

-public fun storage<Ext: drop>(
-    _ext: Ext, self: &Kiosk
-): &Bag \{
-    assert!(is_installed<Ext>(self), EExtensionNotInstalled);
-    &extension<Ext>(self).storage
-}
-
- - - -
- - - -## Function `storage_mut` - -Get mutable access to the extension storage. Can only be performed by -the extension as long as the extension is installed. Disabling the -extension does not prevent it from accessing the storage. - -Potentially dangerous: extension developer can keep data in a Bag -therefore never really allowing the KioskOwner to remove the extension. -However, it is the case with any other solution (1) and this way we -prevent intentional extension freeze when the owner wants to ruin a -trade (2) - eg locking extension while an auction is in progress. - -Extensions should be crafted carefully, and the KioskOwner should be -aware of the risks. - - -

-public fun storage_mut<Ext: drop>(_ext: Ext, self: &mut kiosk::Kiosk): &mut bag::Bag
-
- - - -
-Implementation - - -

-public fun storage_mut<Ext: drop>(
-    _ext: Ext, self: &mut Kiosk
-): &mut Bag \{
-    assert!(is_installed<Ext>(self), EExtensionNotInstalled);
-    &mut extension_mut<Ext>(self).storage
-}
-
- - - -
- - - -## Function `place` - -Protected action: place an item into the Kiosk. Can be performed by an -authorized extension. The extension must have the -place permission or -a -lock permission. - -To prevent non-tradable items from being placed into -Kiosk the method -requires a -TransferPolicy for the placed type to exist. - - -

-public fun place<Ext: drop, T: store, key>(_ext: Ext, self: &mut kiosk::Kiosk, item: T, _policy: &transfer_policy::TransferPolicy<T>)
-
- - - -
-Implementation - - -

-public fun place<Ext: drop, T: key + store>(
-    _ext: Ext, self: &mut Kiosk, item: T, _policy: &TransferPolicy<T>
-) \{
-    assert!(is_installed<Ext>(self), EExtensionNotInstalled);
-    assert!(can_place<Ext>(self) || can_lock<Ext>(self), EExtensionNotAllowed);
-
-    self.place_internal(item)
-}
-
- - - -
- - - -## Function `lock` - -Protected action: lock an item in the Kiosk. Can be performed by an -authorized extension. The extension must have the -lock permission. - - -

-public fun lock<Ext: drop, T: store, key>(_ext: Ext, self: &mut kiosk::Kiosk, item: T, _policy: &transfer_policy::TransferPolicy<T>)
-
- - - -
-Implementation - - -

-public fun lock<Ext: drop, T: key + store>(
-    _ext: Ext, self: &mut Kiosk, item: T, _policy: &TransferPolicy<T>
-) \{
-    assert!(is_installed<Ext>(self), EExtensionNotInstalled);
-    assert!(can_lock<Ext>(self), EExtensionNotAllowed);
-
-    self.lock_internal(item)
-}
-
- - - -
- - - -## Function `is_installed` - -Check whether an extension of type -Ext is installed. - - -

-public fun is_installed<Ext: drop>(self: &kiosk::Kiosk): bool
-
- - - -
-Implementation - - -

-public fun is_installed<Ext: drop>(self: &Kiosk): bool \{
-    df::exists_(self.uid(), ExtensionKey<Ext> \{})
-}
-
- - - -
- - - -## Function `is_enabled` - -Check whether an extension of type -Ext is enabled. - - -

-public fun is_enabled<Ext: drop>(self: &kiosk::Kiosk): bool
-
- - - -
-Implementation - - -

-public fun is_enabled<Ext: drop>(self: &Kiosk): bool \{
-    extension<Ext>(self).is_enabled
-}
-
- - - -
- - - -## Function `can_place` - -Check whether an extension of type -Ext can -place into Kiosk. - - -

-public fun can_place<Ext: drop>(self: &kiosk::Kiosk): bool
-
- - - -
-Implementation - - -

-public fun can_place<Ext: drop>(self: &Kiosk): bool \{
-    is_enabled<Ext>(self) && extension<Ext>(self).permissions & PLACE != 0
-}
-
- - - -
- - - -## Function `can_lock` - -Check whether an extension of type -Ext can -lock items in Kiosk. -Locking also enables -place. - - -

-public fun can_lock<Ext: drop>(self: &kiosk::Kiosk): bool
-
- - - -
-Implementation - - -

-public fun can_lock<Ext: drop>(self: &Kiosk): bool \{
-    is_enabled<Ext>(self) && extension<Ext>(self).permissions & LOCK != 0
-}
-
- - - -
- - - -## Function `extension` - -Internal: get a read-only access to the Extension. - - -

-fun extension<Ext: drop>(self: &kiosk::Kiosk): &kiosk_extension::Extension
-
- - - -
-Implementation - - -

-fun extension<Ext: drop>(self: &Kiosk): &Extension \{
-    df::borrow(self.uid(), ExtensionKey<Ext> \{})
-}
-
- - - -
- - - -## Function `extension_mut` - -Internal: get a mutable access to the Extension. - - -

-fun extension_mut<Ext: drop>(self: &mut kiosk::Kiosk): &mut kiosk_extension::Extension
-
- - - -
-Implementation - - -

-fun extension_mut<Ext: drop>(self: &mut Kiosk): &mut Extension \{
-    df::borrow_mut(self.uid_mut_internal(), ExtensionKey<Ext> \{})
-}
-
- - - -
diff --git a/crates/iota-framework/docs/iota-framework/labeler.mdx b/crates/iota-framework/docs/iota-framework/labeler.mdx deleted file mode 100644 index 2bc9ff3dc7b..00000000000 --- a/crates/iota-framework/docs/iota-framework/labeler.mdx +++ /dev/null @@ -1,137 +0,0 @@ ---- -title: Module `0x2::labeler` ---- -import Link from '@docusaurus/Link'; - - - - -- [Resource `LabelerCap`](#0x2_labeler_LabelerCap) -- [Constants](#@Constants_0) -- [Function `create_labeler_cap`](#0x2_labeler_create_labeler_cap) -- [Function `destroy_labeler_cap`](#0x2_labeler_destroy_labeler_cap) - - -

-use 0x2::object;
-use 0x2::tx_context;
-use 0x2::types;
-
- - - - - -## Resource `LabelerCap` - - -LabelerCap allows to create labels of the specific type -L. -Can be publicly transferred like any other object. - - -

-struct LabelerCap<L> has store, key
-
- - - -
-Fields - - -
-
- -id: object::UID -
-
- -
-
- - -
- - - -## Constants - - - - -Error code for when a type passed to the -create_labeler_cap function is not a one-time witness. - - -

-const ENotOneTimeWitness: u64 = 0;
-
- - - - - -## Function `create_labeler_cap` - -Create a -LabelerCap instance. -Can be created only by consuming a one time witness. - - -

-public fun create_labeler_cap<L: drop>(witness: L, ctx: &mut tx_context::TxContext): labeler::LabelerCap<L>
-
- - - -
-Implementation - - -

-public fun create_labeler_cap<L: drop>(witness: L, ctx: &mut TxContext): LabelerCap<L> \{
-    assert!(iota::types::is_one_time_witness(&witness), ENotOneTimeWitness);
-
-    LabelerCap<L> \{
-        id: object::new(ctx),
-    }
-}
-
- - - -
- - - -## Function `destroy_labeler_cap` - -Delete a -LabelerCap instance. -If a capability is destroyed, it is impossible to add the related labels. - - -

-public fun destroy_labeler_cap<L>(cap: labeler::LabelerCap<L>)
-
- - - -
-Implementation - - -

-public fun destroy_labeler_cap<L>(cap: LabelerCap<L>) \{
-    let LabelerCap<L> \{
-        id,
-    } = cap;
-
-    object::delete(id);
-}
-
- - - -
diff --git a/crates/iota-framework/docs/iota-framework/linked_table.mdx b/crates/iota-framework/docs/iota-framework/linked_table.mdx deleted file mode 100644 index 162249bcc17..00000000000 --- a/crates/iota-framework/docs/iota-framework/linked_table.mdx +++ /dev/null @@ -1,729 +0,0 @@ ---- -title: Module `0x2::linked_table` ---- -import Link from '@docusaurus/Link'; - - -Similar to -iota::table but the values are linked together, allowing for ordered insertion and -removal - - -- [Resource `LinkedTable`](#0x2_linked_table_LinkedTable) -- [Struct `Node`](#0x2_linked_table_Node) -- [Constants](#@Constants_0) -- [Function `new`](#0x2_linked_table_new) -- [Function `front`](#0x2_linked_table_front) -- [Function `back`](#0x2_linked_table_back) -- [Function `push_front`](#0x2_linked_table_push_front) -- [Function `push_back`](#0x2_linked_table_push_back) -- [Function `borrow`](#0x2_linked_table_borrow) -- [Function `borrow_mut`](#0x2_linked_table_borrow_mut) -- [Function `prev`](#0x2_linked_table_prev) -- [Function `next`](#0x2_linked_table_next) -- [Function `remove`](#0x2_linked_table_remove) -- [Function `pop_front`](#0x2_linked_table_pop_front) -- [Function `pop_back`](#0x2_linked_table_pop_back) -- [Function `contains`](#0x2_linked_table_contains) -- [Function `length`](#0x2_linked_table_length) -- [Function `is_empty`](#0x2_linked_table_is_empty) -- [Function `destroy_empty`](#0x2_linked_table_destroy_empty) -- [Function `drop`](#0x2_linked_table_drop) - - -

-use 0x1::option;
-use 0x2::dynamic_field;
-use 0x2::object;
-use 0x2::tx_context;
-
- - - - - -## Resource `LinkedTable` - - - -

-struct LinkedTable<K: copy, drop, store, V: store> has store, key
-
- - - -
-Fields - - -
-
- -id: object::UID -
-
- the ID of this table -
-
- -size: u64 -
-
- the number of key-value pairs in the table -
-
- -head: option::Option<K> -
-
- the front of the table, i.e. the key of the first entry -
-
- -tail: option::Option<K> -
-
- the back of the table, i.e. the key of the last entry -
-
- - -
- - - -## Struct `Node` - - - -

-struct Node<K: copy, drop, store, V: store> has store
-
- - - -
-Fields - - -
-
- -prev: option::Option<K> -
-
- the previous key -
-
- -next: option::Option<K> -
-
- the next key -
-
- -value: V -
-
- the value being stored -
-
- - -
- - - -## Constants - - - - - - -

-const ETableNotEmpty: u64 = 0;
-
- - - - - - - -

-const ETableIsEmpty: u64 = 1;
-
- - - - - -## Function `new` - -Creates a new, empty table - - -

-public fun new<K: copy, drop, store, V: store>(ctx: &mut tx_context::TxContext): linked_table::LinkedTable<K, V>
-
- - - -
-Implementation - - -

-public fun new<K: copy + drop + store, V: store>(ctx: &mut TxContext): LinkedTable<K, V> \{
-    LinkedTable \{
-        id: object::new(ctx),
-        size: 0,
-        head: option::none(),
-        tail: option::none(),
-    }
-}
-
- - - -
- - - -## Function `front` - -Returns the key for the first element in the table, or None if the table is empty - - -

-public fun front<K: copy, drop, store, V: store>(table: &linked_table::LinkedTable<K, V>): &option::Option<K>
-
- - - -
-Implementation - - -

-public fun front<K: copy + drop + store, V: store>(table: &LinkedTable<K, V>): &Option<K> \{
-    &table.head
-}
-
- - - -
- - - -## Function `back` - -Returns the key for the last element in the table, or None if the table is empty - - -

-public fun back<K: copy, drop, store, V: store>(table: &linked_table::LinkedTable<K, V>): &option::Option<K>
-
- - - -
-Implementation - - -

-public fun back<K: copy + drop + store, V: store>(table: &LinkedTable<K, V>): &Option<K> \{
-    &table.tail
-}
-
- - - -
- - - -## Function `push_front` - -Inserts a key-value pair at the front of the table, i.e. the newly inserted pair will be -the first element in the table -Aborts with -iota::dynamic_field::EFieldAlreadyExists if the table already has an entry with -that key -k: K. - - -

-public fun push_front<K: copy, drop, store, V: store>(table: &mut linked_table::LinkedTable<K, V>, k: K, value: V)
-
- - - -
-Implementation - - -

-public fun push_front<K: copy + drop + store, V: store>(
-    table: &mut LinkedTable<K, V>,
-    k: K,
-    value: V,
-) \{
-    let old_head = table.head.swap_or_fill(k);
-    if (table.tail.is_none()) table.tail.fill(k);
-    let prev = option::none();
-    let next = if (old_head.is_some()) \{
-        let old_head_k = old_head.destroy_some();
-        field::borrow_mut<K, Node<K, V>>(&mut table.id, old_head_k).prev = option::some(k);
-        option::some(old_head_k)
-    } else \{
-        option::none()
-    };
-    field::add(&mut table.id, k, Node \{ prev, next, value });
-    table.size = table.size + 1;
-}
-
- - - -
- - - -## Function `push_back` - -Inserts a key-value pair at the back of the table, i.e. the newly inserted pair will be -the last element in the table -Aborts with -iota::dynamic_field::EFieldAlreadyExists if the table already has an entry with -that key -k: K. - - -

-public fun push_back<K: copy, drop, store, V: store>(table: &mut linked_table::LinkedTable<K, V>, k: K, value: V)
-
- - - -
-Implementation - - -

-public fun push_back<K: copy + drop + store, V: store>(
-    table: &mut LinkedTable<K, V>,
-    k: K,
-    value: V,
-) \{
-    if (table.head.is_none()) table.head.fill(k);
-    let old_tail = table.tail.swap_or_fill(k);
-    let prev = if (old_tail.is_some()) \{
-        let old_tail_k = old_tail.destroy_some();
-        field::borrow_mut<K, Node<K, V>>(&mut table.id, old_tail_k).next = option::some(k);
-        option::some(old_tail_k)
-    } else \{
-        option::none()
-    };
-    let next = option::none();
-    field::add(&mut table.id, k, Node \{ prev, next, value });
-    table.size = table.size + 1;
-}
-
- - - -
- - - -## Function `borrow` - -Immutable borrows the value associated with the key in the table -table: &LinkedTable<K, V>. -Aborts with -iota::dynamic_field::EFieldDoesNotExist if the table does not have an entry with -that key -k: K. - - -

-public fun borrow<K: copy, drop, store, V: store>(table: &linked_table::LinkedTable<K, V>, k: K): &V
-
- - - -
-Implementation - - -

-public fun borrow<K: copy + drop + store, V: store>(table: &LinkedTable<K, V>, k: K): &V \{
-    &field::borrow<K, Node<K, V>>(&table.id, k).value
-}
-
- - - -
- - - -## Function `borrow_mut` - -Mutably borrows the value associated with the key in the table -table: &mut LinkedTable<K, V>. -Aborts with -iota::dynamic_field::EFieldDoesNotExist if the table does not have an entry with -that key -k: K. - - -

-public fun borrow_mut<K: copy, drop, store, V: store>(table: &mut linked_table::LinkedTable<K, V>, k: K): &mut V
-
- - - -
-Implementation - - -

-public fun borrow_mut<K: copy + drop + store, V: store>(
-    table: &mut LinkedTable<K, V>,
-    k: K,
-): &mut V \{
-    &mut field::borrow_mut<K, Node<K, V>>(&mut table.id, k).value
-}
-
- - - -
- - - -## Function `prev` - -Borrows the key for the previous entry of the specified key -k: K in the table - -table: &LinkedTable<K, V>. Returns None if the entry does not have a predecessor. -Aborts with -iota::dynamic_field::EFieldDoesNotExist if the table does not have an entry with -that key -k: K - - -

-public fun prev<K: copy, drop, store, V: store>(table: &linked_table::LinkedTable<K, V>, k: K): &option::Option<K>
-
- - - -
-Implementation - - -

-public fun prev<K: copy + drop + store, V: store>(table: &LinkedTable<K, V>, k: K): &Option<K> \{
-    &field::borrow<K, Node<K, V>>(&table.id, k).prev
-}
-
- - - -
- - - -## Function `next` - -Borrows the key for the next entry of the specified key -k: K in the table - -table: &LinkedTable<K, V>. Returns None if the entry does not have a predecessor. -Aborts with -iota::dynamic_field::EFieldDoesNotExist if the table does not have an entry with -that key -k: K - - -

-public fun next<K: copy, drop, store, V: store>(table: &linked_table::LinkedTable<K, V>, k: K): &option::Option<K>
-
- - - -
-Implementation - - -

-public fun next<K: copy + drop + store, V: store>(table: &LinkedTable<K, V>, k: K): &Option<K> \{
-    &field::borrow<K, Node<K, V>>(&table.id, k).next
-}
-
- - - -
- - - -## Function `remove` - -Removes the key-value pair in the table -table: &mut LinkedTable<K, V> and returns the value. -This splices the element out of the ordering. -Aborts with -iota::dynamic_field::EFieldDoesNotExist if the table does not have an entry with -that key -k: K. Note: this is also what happens when the table is empty. - - -

-public fun remove<K: copy, drop, store, V: store>(table: &mut linked_table::LinkedTable<K, V>, k: K): V
-
- - - -
-Implementation - - -

-public fun remove<K: copy + drop + store, V: store>(table: &mut LinkedTable<K, V>, k: K): V \{
-    let Node<K, V> \{ prev, next, value } = field::remove(&mut table.id, k);
-    table.size = table.size - 1;
-    if (prev.is_some()) \{
-        field::borrow_mut<K, Node<K, V>>(&mut table.id, *prev.borrow()).next = next
-    };
-    if (next.is_some()) \{
-        field::borrow_mut<K, Node<K, V>>(&mut table.id, *next.borrow()).prev = prev
-    };
-    if (table.head.borrow() == &k) table.head = next;
-    if (table.tail.borrow() == &k) table.tail = prev;
-    value
-}
-
- - - -
- - - -## Function `pop_front` - -Removes the front of the table -table: &mut LinkedTable<K, V> and returns the value. -Aborts with -ETableIsEmpty if the table is empty - - -

-public fun pop_front<K: copy, drop, store, V: store>(table: &mut linked_table::LinkedTable<K, V>): (K, V)
-
- - - -
-Implementation - - -

-public fun pop_front<K: copy + drop + store, V: store>(table: &mut LinkedTable<K, V>): (K, V) \{
-    assert!(table.head.is_some(), ETableIsEmpty);
-    let head = *table.head.borrow();
-    (head, table.remove(head))
-}
-
- - - -
- - - -## Function `pop_back` - -Removes the back of the table -table: &mut LinkedTable<K, V> and returns the value. -Aborts with -ETableIsEmpty if the table is empty - - -

-public fun pop_back<K: copy, drop, store, V: store>(table: &mut linked_table::LinkedTable<K, V>): (K, V)
-
- - - -
-Implementation - - -

-public fun pop_back<K: copy + drop + store, V: store>(table: &mut LinkedTable<K, V>): (K, V) \{
-    assert!(table.tail.is_some(), ETableIsEmpty);
-    let tail = *table.tail.borrow();
-    (tail, table.remove(tail))
-}
-
- - - -
- - - -## Function `contains` - -Returns true iff there is a value associated with the key -k: K in table - -table: &LinkedTable<K, V> - - -

-public fun contains<K: copy, drop, store, V: store>(table: &linked_table::LinkedTable<K, V>, k: K): bool
-
- - - -
-Implementation - - -

-public fun contains<K: copy + drop + store, V: store>(table: &LinkedTable<K, V>, k: K): bool \{
-    field::exists_with_type<K, Node<K, V>>(&table.id, k)
-}
-
- - - -
- - - -## Function `length` - -Returns the size of the table, the number of key-value pairs - - -

-public fun length<K: copy, drop, store, V: store>(table: &linked_table::LinkedTable<K, V>): u64
-
- - - -
-Implementation - - -

-public fun length<K: copy + drop + store, V: store>(table: &LinkedTable<K, V>): u64 \{
-    table.size
-}
-
- - - -
- - - -## Function `is_empty` - -Returns true iff the table is empty (if -length returns -0) - - -

-public fun is_empty<K: copy, drop, store, V: store>(table: &linked_table::LinkedTable<K, V>): bool
-
- - - -
-Implementation - - -

-public fun is_empty<K: copy + drop + store, V: store>(table: &LinkedTable<K, V>): bool \{
-    table.size == 0
-}
-
- - - -
- - - -## Function `destroy_empty` - -Destroys an empty table -Aborts with -ETableNotEmpty if the table still contains values - - -

-public fun destroy_empty<K: copy, drop, store, V: store>(table: linked_table::LinkedTable<K, V>)
-
- - - -
-Implementation - - -

-public fun destroy_empty<K: copy + drop + store, V: store>(table: LinkedTable<K, V>) \{
-    let LinkedTable \{ id, size, head: _, tail: _ } = table;
-    assert!(size == 0, ETableNotEmpty);
-    id.delete()
-}
-
- - - -
- - - -## Function `drop` - -Drop a possibly non-empty table. -Usable only if the value type -V has the -drop ability - - -

-public fun drop<K: copy, drop, store, V: drop, store>(table: linked_table::LinkedTable<K, V>)
-
- - - -
-Implementation - - -

-public fun drop<K: copy + drop + store, V: drop + store>(table: LinkedTable<K, V>) \{
-    let LinkedTable \{ id, size: _, head: _, tail: _ } = table;
-    id.delete()
-}
-
- - - -
diff --git a/crates/iota-framework/docs/iota-framework/math.mdx b/crates/iota-framework/docs/iota-framework/math.mdx deleted file mode 100644 index a2a8597863f..00000000000 --- a/crates/iota-framework/docs/iota-framework/math.mdx +++ /dev/null @@ -1,320 +0,0 @@ ---- -title: Module `0x2::math` ---- -import Link from '@docusaurus/Link'; - - -Basic math for nicer programmability - - -- [Function `max`](#0x2_math_max) -- [Function `min`](#0x2_math_min) -- [Function `diff`](#0x2_math_diff) -- [Function `pow`](#0x2_math_pow) -- [Function `sqrt`](#0x2_math_sqrt) -- [Function `sqrt_u128`](#0x2_math_sqrt_u128) -- [Function `divide_and_round_up`](#0x2_math_divide_and_round_up) - - -

-
- - - - - -## Function `max` - -Return the larger of -x and -y - - -

-public fun max(x: u64, y: u64): u64
-
- - - -
-Implementation - - -

-public fun max(x: u64, y: u64): u64 \{
-    if (x > y) \{
-        x
-    } else \{
-        y
-    }
-}
-
- - - -
- - - -## Function `min` - -Return the smaller of -x and -y - - -

-public fun min(x: u64, y: u64): u64
-
- - - -
-Implementation - - -

-public fun min(x: u64, y: u64): u64 \{
-    if (x < y) \{
-        x
-    } else \{
-        y
-    }
-}
-
- - - -
- - - -## Function `diff` - -Return the absolute value of x - y - - -

-public fun diff(x: u64, y: u64): u64
-
- - - -
-Implementation - - -

-public fun diff(x: u64, y: u64): u64 \{
-    if (x > y) \{
-        x - y
-    } else \{
-        y - x
-    }
-}
-
- - - -
- - - -## Function `pow` - -Return the value of a base raised to a power - - -

-public fun pow(base: u64, exponent: u8): u64
-
- - - -
-Implementation - - -

-public fun pow(mut base: u64, mut exponent: u8): u64 \{
-    let mut res = 1;
-    while (exponent >= 1) \{
-        if (exponent % 2 == 0) \{
-            base = base * base;
-            exponent = exponent / 2;
-        } else \{
-            res = res * base;
-            exponent = exponent - 1;
-        }
-    };
-
-    res
-}
-
- - - -
- - - -## Function `sqrt` - -Get a nearest lower integer Square Root for -x. Given that this -function can only operate with integers, it is impossible -to get perfect (or precise) integer square root for some numbers. - -Example: -``` -math::sqrt(9) => 3 -math::sqrt(8) => 2 // the nearest lower square root is 4; -``` - -In integer math, one of the possible ways to get results with more -precision is to use higher values or temporarily multiply the -value by some bigger number. Ideally if this is a square of 10 or 100. - -Example: -``` -math::sqrt(8) => 2; -math::sqrt(8 * 10000) => 282; -// now we can use this value as if it was 2.82; -// but to get the actual result, this value needs -// to be divided by 100 (because sqrt(10000)). - - -math::sqrt(8 * 1000000) => 2828; // same as above, 2828 / 1000 (2.828) -``` - - -

-public fun sqrt(x: u64): u64
-
- - - -
-Implementation - - -

-public fun sqrt(x: u64): u64 \{
-    let mut bit = 1u128 << 64;
-    let mut res = 0u128;
-    let mut x = x as u128;
-
-    while (bit != 0) \{
-        if (x >= res + bit) \{
-            x = x - (res + bit);
-            res = (res >> 1) + bit;
-        } else \{
-            res = res >> 1;
-        };
-        bit = bit >> 2;
-    };
-
-    res as u64
-}
-
- - - -
- - - -## Function `sqrt_u128` - -Similar to math::sqrt, but for u128 numbers. Get a nearest lower integer Square Root for -x. Given that this -function can only operate with integers, it is impossible -to get perfect (or precise) integer square root for some numbers. - -Example: -``` -math::sqrt_u128(9) => 3 -math::sqrt_u128(8) => 2 // the nearest lower square root is 4; -``` - -In integer math, one of the possible ways to get results with more -precision is to use higher values or temporarily multiply the -value by some bigger number. Ideally if this is a square of 10 or 100. - -Example: -``` -math::sqrt_u128(8) => 2; -math::sqrt_u128(8 * 10000) => 282; -// now we can use this value as if it was 2.82; -// but to get the actual result, this value needs -// to be divided by 100 (because sqrt_u128(10000)). - - -math::sqrt_u128(8 * 1000000) => 2828; // same as above, 2828 / 1000 (2.828) -``` - - -

-public fun sqrt_u128(x: u128): u128
-
- - - -
-Implementation - - -

-public fun sqrt_u128(x: u128): u128 \{
-    let mut bit = 1u256 << 128;
-    let mut res = 0u256;
-    let mut x = x as u256;
-
-    while (bit != 0) \{
-        if (x >= res + bit) \{
-            x = x - (res + bit);
-            res = (res >> 1) + bit;
-        } else \{
-            res = res >> 1;
-        };
-        bit = bit >> 2;
-    };
-
-    res as u128
-}
-
- - - -
- - - -## Function `divide_and_round_up` - -Calculate x / y, but round up the result. - - -

-public fun divide_and_round_up(x: u64, y: u64): u64
-
- - - -
-Implementation - - -

-public fun divide_and_round_up(x: u64, y: u64): u64 \{
-    if (x % y == 0) \{
-        x / y
-    } else \{
-        x / y + 1
-    }
-}
-
- - - -
diff --git a/crates/iota-framework/docs/iota-framework/object.mdx b/crates/iota-framework/docs/iota-framework/object.mdx deleted file mode 100644 index 49ae70445ee..00000000000 --- a/crates/iota-framework/docs/iota-framework/object.mdx +++ /dev/null @@ -1,883 +0,0 @@ ---- -title: Module `0x2::object` ---- -import Link from '@docusaurus/Link'; - - -Iota object identifiers - - -- [Struct `ID`](#0x2_object_ID) -- [Struct `UID`](#0x2_object_UID) -- [Constants](#@Constants_0) -- [Function `id_to_bytes`](#0x2_object_id_to_bytes) -- [Function `id_to_address`](#0x2_object_id_to_address) -- [Function `id_from_bytes`](#0x2_object_id_from_bytes) -- [Function `id_from_address`](#0x2_object_id_from_address) -- [Function `iota_system_state`](#0x2_object_iota_system_state) -- [Function `clock`](#0x2_object_clock) -- [Function `authenticator_state`](#0x2_object_authenticator_state) -- [Function `randomness_state`](#0x2_object_randomness_state) -- [Function `iota_deny_list_object_id`](#0x2_object_iota_deny_list_object_id) -- [Function `uid_as_inner`](#0x2_object_uid_as_inner) -- [Function `uid_to_inner`](#0x2_object_uid_to_inner) -- [Function `uid_to_bytes`](#0x2_object_uid_to_bytes) -- [Function `uid_to_address`](#0x2_object_uid_to_address) -- [Function `new`](#0x2_object_new) -- [Function `delete`](#0x2_object_delete) -- [Function `id`](#0x2_object_id) -- [Function `borrow_id`](#0x2_object_borrow_id) -- [Function `id_bytes`](#0x2_object_id_bytes) -- [Function `id_address`](#0x2_object_id_address) -- [Function `borrow_uid`](#0x2_object_borrow_uid) -- [Function `new_uid_from_hash`](#0x2_object_new_uid_from_hash) -- [Function `delete_impl`](#0x2_object_delete_impl) -- [Function `record_new_uid`](#0x2_object_record_new_uid) - - -

-use 0x1::bcs;
-use 0x2::address;
-use 0x2::tx_context;
-
- - - - - -## Struct `ID` - -An object ID. This is used to reference Iota Objects. -This is *not* guaranteed to be globally unique--anyone can create an -ID from a -UID or -from an object, and ID's can be freely copied and dropped. -Here, the values are not globally unique because there can be multiple values of type -ID -with the same underlying bytes. For example, -object::id(&obj) can be called as many times -as you want for a given -obj, and each -ID value will be identical. - - -

-struct ID has copy, drop, store
-
- - - -
-Fields - - -
-
- -bytes: address -
-
- -
-
- - -
- - - -## Struct `UID` - -Globally unique IDs that define an object's ID in storage. Any Iota Object, that is a struct -with the -key ability, must have -id: UID as its first field. -These are globally unique in the sense that no two values of type -UID are ever equal, in -other words for any two values -id1: UID and -id2: UID, -id1 != -id2. -This is a privileged type that can only be derived from a -TxContext. - -UID doesn't have the -drop ability, so deleting a -UID requires a call to -delete. - - -

-struct UID has store
-
- - - -
-Fields - - -
-
- -id: object::ID -
-
- -
-
- - -
- - - -## Constants - - - - -Sender is not @0x0 the system address. - - -

-const ENotSystemAddress: u64 = 0;
-
- - - - - -The hardcoded ID for the singleton AuthenticatorState Object. - - -

-const IOTA_AUTHENTICATOR_STATE_ID: address = 7;
-
- - - - - -The hardcoded ID for the singleton Clock Object. - - -

-const IOTA_CLOCK_OBJECT_ID: address = 6;
-
- - - - - -The hardcoded ID for the singleton DenyList. - - -

-const IOTA_DENY_LIST_OBJECT_ID: address = 403;
-
- - - - - -The hardcoded ID for the singleton Random Object. - - -

-const IOTA_RANDOM_ID: address = 8;
-
- - - - - -The hardcoded ID for the singleton Iota System State Object. - - -

-const IOTA_SYSTEM_STATE_OBJECT_ID: address = 5;
-
- - - - - -## Function `id_to_bytes` - -Get the raw bytes of a -ID - - -

-public fun id_to_bytes(id: &object::ID): vector<u8>
-
- - - -
-Implementation - - -

-public fun id_to_bytes(id: &ID): vector<u8> \{
-    bcs::to_bytes(&id.bytes)
-}
-
- - - -
- - - -## Function `id_to_address` - -Get the inner bytes of -id as an address. - - -

-public fun id_to_address(id: &object::ID): address
-
- - - -
-Implementation - - -

-public fun id_to_address(id: &ID): address \{
-    id.bytes
-}
-
- - - -
- - - -## Function `id_from_bytes` - -Make an -ID from raw bytes. - - -

-public fun id_from_bytes(bytes: vector<u8>): object::ID
-
- - - -
-Implementation - - -

-public fun id_from_bytes(bytes: vector<u8>): ID \{
-    address::from_bytes(bytes).to_id()
-}
-
- - - -
- - - -## Function `id_from_address` - -Make an -ID from an address. - - -

-public fun id_from_address(bytes: address): object::ID
-
- - - -
-Implementation - - -

-public fun id_from_address(bytes: address): ID \{
-    ID \{ bytes }
-}
-
- - - -
- - - -## Function `iota_system_state` - -Create the -UID for the singleton -IotaSystemState object. -This should only be called once from -iota_system. - - -

-fun iota_system_state(ctx: &tx_context::TxContext): object::UID
-
- - - -
-Implementation - - -

-fun iota_system_state(ctx: &TxContext): UID \{
-    assert!(ctx.sender() == @0x0, ENotSystemAddress);
-    UID \{
-        id: ID \{ bytes: IOTA_SYSTEM_STATE_OBJECT_ID },
-    }
-}
-
- - - -
- - - -## Function `clock` - -Create the -UID for the singleton -Clock object. -This should only be called once from -clock. - - -

-public(friend) fun clock(): object::UID
-
- - - -
-Implementation - - -

-public(package) fun clock(): UID \{
-    UID \{
-        id: ID \{ bytes: IOTA_CLOCK_OBJECT_ID }
-    }
-}
-
- - - -
- - - -## Function `authenticator_state` - -Create the -UID for the singleton -AuthenticatorState object. -This should only be called once from -authenticator_state. - - -

-public(friend) fun authenticator_state(): object::UID
-
- - - -
-Implementation - - -

-public(package) fun authenticator_state(): UID \{
-    UID \{
-        id: ID \{ bytes: IOTA_AUTHENTICATOR_STATE_ID }
-    }
-}
-
- - - -
- - - -## Function `randomness_state` - -Create the -UID for the singleton -Random object. -This should only be called once from -random. - - -

-public(friend) fun randomness_state(): object::UID
-
- - - -
-Implementation - - -

-public(package) fun randomness_state(): UID \{
-    UID \{
-        id: ID \{ bytes: IOTA_RANDOM_ID }
-    }
-}
-
- - - -
- - - -## Function `iota_deny_list_object_id` - -Create the -UID for the singleton -DenyList object. -This should only be called once from -deny_list. - - -

-public(friend) fun iota_deny_list_object_id(): object::UID
-
- - - -
-Implementation - - -

-public(package) fun iota_deny_list_object_id(): UID \{
-    UID \{
-        id: ID \{ bytes: IOTA_DENY_LIST_OBJECT_ID }
-    }
-}
-
- - - -
- - - -## Function `uid_as_inner` - -Get the inner -ID of -uid - - -

-public fun uid_as_inner(uid: &object::UID): &object::ID
-
- - - -
-Implementation - - -

-public fun uid_as_inner(uid: &UID): &ID \{
-    &uid.id
-}
-
- - - -
- - - -## Function `uid_to_inner` - -Get the raw bytes of a -uid's inner -ID - - -

-public fun uid_to_inner(uid: &object::UID): object::ID
-
- - - -
-Implementation - - -

-public fun uid_to_inner(uid: &UID): ID \{
-    uid.id
-}
-
- - - -
- - - -## Function `uid_to_bytes` - -Get the raw bytes of a -UID - - -

-public fun uid_to_bytes(uid: &object::UID): vector<u8>
-
- - - -
-Implementation - - -

-public fun uid_to_bytes(uid: &UID): vector<u8> \{
-    bcs::to_bytes(&uid.id.bytes)
-}
-
- - - -
- - - -## Function `uid_to_address` - -Get the inner bytes of -id as an address. - - -

-public fun uid_to_address(uid: &object::UID): address
-
- - - -
-Implementation - - -

-public fun uid_to_address(uid: &UID): address \{
-    uid.id.bytes
-}
-
- - - -
- - - -## Function `new` - -Create a new object. Returns the -UID that must be stored in a Iota object. -This is the only way to create -UIDs. - - -

-public fun new(ctx: &mut tx_context::TxContext): object::UID
-
- - - -
-Implementation - - -

-public fun new(ctx: &mut TxContext): UID \{
-    UID \{
-        id: ID \{ bytes: ctx.fresh_object_address() },
-    }
-}
-
- - - -
- - - -## Function `delete` - -Delete the object and it's -UID. This is the only way to eliminate a -UID. - - -

-public fun delete(id: object::UID)
-
- - - -
-Implementation - - -

-public fun delete(id: UID) \{
-    let UID \{ id: ID \{ bytes } } = id;
-    delete_impl(bytes)
-}
-
- - - -
- - - -## Function `id` - -Get the underlying -ID of -obj - - -

-public fun id<T: key>(obj: &T): object::ID
-
- - - -
-Implementation - - -

-public fun id<T: key>(obj: &T): ID \{
-    borrow_uid(obj).id
-}
-
- - - -
- - - -## Function `borrow_id` - -Borrow the underlying -ID of -obj - - -

-public fun borrow_id<T: key>(obj: &T): &object::ID
-
- - - -
-Implementation - - -

-public fun borrow_id<T: key>(obj: &T): &ID \{
-    &borrow_uid(obj).id
-}
-
- - - -
- - - -## Function `id_bytes` - -Get the raw bytes for the underlying -ID of -obj - - -

-public fun id_bytes<T: key>(obj: &T): vector<u8>
-
- - - -
-Implementation - - -

-public fun id_bytes<T: key>(obj: &T): vector<u8> \{
-    bcs::to_bytes(&borrow_uid(obj).id)
-}
-
- - - -
- - - -## Function `id_address` - -Get the inner bytes for the underlying -ID of -obj - - -

-public fun id_address<T: key>(obj: &T): address
-
- - - -
-Implementation - - -

-public fun id_address<T: key>(obj: &T): address \{
-    borrow_uid(obj).id.bytes
-}
-
- - - -
- - - -## Function `borrow_uid` - -Get the -UID for -obj. -Safe because Iota has an extra bytecode verifier pass that forces every struct with -the -key ability to have a distinguished -UID field. -Cannot be made public as the access to -UID for a given object must be privileged, and -restrictable in the object's module. - - -

-fun borrow_uid<T: key>(obj: &T): &object::UID
-
- - - -
-Implementation - - -

-native fun borrow_uid<T: key>(obj: &T): &UID;
-
- - - -
- - - -## Function `new_uid_from_hash` - -Generate a new UID specifically used for creating a UID from a hash - - -

-public(friend) fun new_uid_from_hash(bytes: address): object::UID
-
- - - -
-Implementation - - -

-public(package) fun new_uid_from_hash(bytes: address): UID \{
-    record_new_uid(bytes);
-    UID \{ id: ID \{ bytes } }
-}
-
- - - -
- - - -## Function `delete_impl` - - - -

-fun delete_impl(id: address)
-
- - - -
-Implementation - - -

-native fun delete_impl(id: address);
-
- - - -
- - - -## Function `record_new_uid` - - - -

-fun record_new_uid(id: address)
-
- - - -
-Implementation - - -

-native fun record_new_uid(id: address);
-
- - - -
diff --git a/crates/iota-framework/docs/iota-framework/object_bag.mdx b/crates/iota-framework/docs/iota-framework/object_bag.mdx deleted file mode 100644 index d357ad4eea2..00000000000 --- a/crates/iota-framework/docs/iota-framework/object_bag.mdx +++ /dev/null @@ -1,435 +0,0 @@ ---- -title: Module `0x2::object_bag` ---- -import Link from '@docusaurus/Link'; - - -Similar to -iota::bag, an -ObjectBag is a heterogeneous map-like collection. But unlike - -iota::bag, the values bound to these dynamic fields _must_ be objects themselves. This allows -for the objects to still exist in storage, which may be important for external tools. -The difference is otherwise not observable from within Move. - - -- [Resource `ObjectBag`](#0x2_object_bag_ObjectBag) -- [Constants](#@Constants_0) -- [Function `new`](#0x2_object_bag_new) -- [Function `add`](#0x2_object_bag_add) -- [Function `borrow`](#0x2_object_bag_borrow) -- [Function `borrow_mut`](#0x2_object_bag_borrow_mut) -- [Function `remove`](#0x2_object_bag_remove) -- [Function `contains`](#0x2_object_bag_contains) -- [Function `contains_with_type`](#0x2_object_bag_contains_with_type) -- [Function `length`](#0x2_object_bag_length) -- [Function `is_empty`](#0x2_object_bag_is_empty) -- [Function `destroy_empty`](#0x2_object_bag_destroy_empty) -- [Function `value_id`](#0x2_object_bag_value_id) - - -

-use 0x1::option;
-use 0x2::dynamic_object_field;
-use 0x2::object;
-use 0x2::tx_context;
-
- - - - - -## Resource `ObjectBag` - - - -

-struct ObjectBag has store, key
-
- - - -
-Fields - - -
-
- -id: object::UID -
-
- the ID of this bag -
-
- -size: u64 -
-
- the number of key-value pairs in the bag -
-
- - -
- - - -## Constants - - - - - - -

-const EBagNotEmpty: u64 = 0;
-
- - - - - -## Function `new` - -Creates a new, empty bag - - -

-public fun new(ctx: &mut tx_context::TxContext): object_bag::ObjectBag
-
- - - -
-Implementation - - -

-public fun new(ctx: &mut TxContext): ObjectBag \{
-    ObjectBag \{
-        id: object::new(ctx),
-        size: 0,
-    }
-}
-
- - - -
- - - -## Function `add` - -Adds a key-value pair to the bag -bag: &mut ObjectBag -Aborts with -iota::dynamic_field::EFieldAlreadyExists if the bag already has an entry with -that key -k: K. - - -

-public fun add<K: copy, drop, store, V: store, key>(bag: &mut object_bag::ObjectBag, k: K, v: V)
-
- - - -
-Implementation - - -

-public fun add<K: copy + drop + store, V: key + store>(bag: &mut ObjectBag, k: K, v: V) \{
-    ofield::add(&mut bag.id, k, v);
-    bag.size = bag.size + 1;
-}
-
- - - -
- - - -## Function `borrow` - -Immutably borrows the value associated with the key in the bag -bag: &ObjectBag. -Aborts with -iota::dynamic_field::EFieldDoesNotExist if the bag does not have an entry with -that key -k: K. -Aborts with -iota::dynamic_field::EFieldTypeMismatch if the bag has an entry for the key, but -the value does not have the specified type. - - -

-public fun borrow<K: copy, drop, store, V: store, key>(bag: &object_bag::ObjectBag, k: K): &V
-
- - - -
-Implementation - - -

-public fun borrow<K: copy + drop + store, V: key + store>(bag: &ObjectBag, k: K): &V \{
-    ofield::borrow(&bag.id, k)
-}
-
- - - -
- - - -## Function `borrow_mut` - -Mutably borrows the value associated with the key in the bag -bag: &mut ObjectBag. -Aborts with -iota::dynamic_field::EFieldDoesNotExist if the bag does not have an entry with -that key -k: K. -Aborts with -iota::dynamic_field::EFieldTypeMismatch if the bag has an entry for the key, but -the value does not have the specified type. - - -

-public fun borrow_mut<K: copy, drop, store, V: store, key>(bag: &mut object_bag::ObjectBag, k: K): &mut V
-
- - - -
-Implementation - - -

-public fun borrow_mut<K: copy + drop + store, V: key + store>(bag: &mut ObjectBag, k: K): &mut V \{
-    ofield::borrow_mut(&mut bag.id, k)
-}
-
- - - -
- - - -## Function `remove` - -Mutably borrows the key-value pair in the bag -bag: &mut ObjectBag and returns the value. -Aborts with -iota::dynamic_field::EFieldDoesNotExist if the bag does not have an entry with -that key -k: K. -Aborts with -iota::dynamic_field::EFieldTypeMismatch if the bag has an entry for the key, but -the value does not have the specified type. - - -

-public fun remove<K: copy, drop, store, V: store, key>(bag: &mut object_bag::ObjectBag, k: K): V
-
- - - -
-Implementation - - -

-public fun remove<K: copy + drop + store, V: key + store>(bag: &mut ObjectBag, k: K): V \{
-    let v = ofield::remove(&mut bag.id, k);
-    bag.size = bag.size - 1;
-    v
-}
-
- - - -
- - - -## Function `contains` - -Returns true iff there is an value associated with the key -k: K in the bag -bag: &ObjectBag - - -

-public fun contains<K: copy, drop, store>(bag: &object_bag::ObjectBag, k: K): bool
-
- - - -
-Implementation - - -

-public fun contains<K: copy + drop + store>(bag: &ObjectBag, k: K): bool \{
-    ofield::exists_<K>(&bag.id, k)
-}
-
- - - -
- - - -## Function `contains_with_type` - -Returns true iff there is an value associated with the key -k: K in the bag -bag: &ObjectBag -with an assigned value of type -V - - -

-public fun contains_with_type<K: copy, drop, store, V: store, key>(bag: &object_bag::ObjectBag, k: K): bool
-
- - - -
-Implementation - - -

-public fun contains_with_type<K: copy + drop + store, V: key + store>(bag: &ObjectBag, k: K): bool \{
-    ofield::exists_with_type<K, V>(&bag.id, k)
-}
-
- - - -
- - - -## Function `length` - -Returns the size of the bag, the number of key-value pairs - - -

-public fun length(bag: &object_bag::ObjectBag): u64
-
- - - -
-Implementation - - -

-public fun length(bag: &ObjectBag): u64 \{
-    bag.size
-}
-
- - - -
- - - -## Function `is_empty` - -Returns true iff the bag is empty (if -length returns -0) - - -

-public fun is_empty(bag: &object_bag::ObjectBag): bool
-
- - - -
-Implementation - - -

-public fun is_empty(bag: &ObjectBag): bool \{
-    bag.size == 0
-}
-
- - - -
- - - -## Function `destroy_empty` - -Destroys an empty bag -Aborts with -EBagNotEmpty if the bag still contains values - - -

-public fun destroy_empty(bag: object_bag::ObjectBag)
-
- - - -
-Implementation - - -

-public fun destroy_empty(bag: ObjectBag) \{
-    let ObjectBag \{ id, size } = bag;
-    assert!(size == 0, EBagNotEmpty);
-    id.delete()
-}
-
- - - -
- - - -## Function `value_id` - -Returns the ID of the object associated with the key if the bag has an entry with key -k: K -Returns none otherwise - - -

-public fun value_id<K: copy, drop, store>(bag: &object_bag::ObjectBag, k: K): option::Option<object::ID>
-
- - - -
-Implementation - - -

-public fun value_id<K: copy + drop + store>(bag: &ObjectBag, k: K): Option<ID> \{
-    ofield::id(&bag.id, k)
-}
-
- - - -
diff --git a/crates/iota-framework/docs/iota-framework/object_table.mdx b/crates/iota-framework/docs/iota-framework/object_table.mdx deleted file mode 100644 index f6b0a78949e..00000000000 --- a/crates/iota-framework/docs/iota-framework/object_table.mdx +++ /dev/null @@ -1,401 +0,0 @@ ---- -title: Module `0x2::object_table` ---- -import Link from '@docusaurus/Link'; - - -Similar to -iota::table, an -ObjectTable<K, V> is a map-like collection. But unlike - -iota::table, the values bound to these dynamic fields _must_ be objects themselves. This allows -for the objects to still exist within in storage, which may be important for external tools. -The difference is otherwise not observable from within Move. - - -- [Resource `ObjectTable`](#0x2_object_table_ObjectTable) -- [Constants](#@Constants_0) -- [Function `new`](#0x2_object_table_new) -- [Function `add`](#0x2_object_table_add) -- [Function `borrow`](#0x2_object_table_borrow) -- [Function `borrow_mut`](#0x2_object_table_borrow_mut) -- [Function `remove`](#0x2_object_table_remove) -- [Function `contains`](#0x2_object_table_contains) -- [Function `length`](#0x2_object_table_length) -- [Function `is_empty`](#0x2_object_table_is_empty) -- [Function `destroy_empty`](#0x2_object_table_destroy_empty) -- [Function `value_id`](#0x2_object_table_value_id) - - -

-use 0x1::option;
-use 0x2::dynamic_object_field;
-use 0x2::object;
-use 0x2::tx_context;
-
- - - - - -## Resource `ObjectTable` - - - -

-struct ObjectTable<K: copy, drop, store, V: store, key> has store, key
-
- - - -
-Fields - - -
-
- -id: object::UID -
-
- the ID of this table -
-
- -size: u64 -
-
- the number of key-value pairs in the table -
-
- - -
- - - -## Constants - - - - - - -

-const ETableNotEmpty: u64 = 0;
-
- - - - - -## Function `new` - -Creates a new, empty table - - -

-public fun new<K: copy, drop, store, V: store, key>(ctx: &mut tx_context::TxContext): object_table::ObjectTable<K, V>
-
- - - -
-Implementation - - -

-public fun new<K: copy + drop + store, V: key + store>(ctx: &mut TxContext): ObjectTable<K, V> \{
-    ObjectTable \{
-        id: object::new(ctx),
-        size: 0,
-    }
-}
-
- - - -
- - - -## Function `add` - -Adds a key-value pair to the table -table: &mut ObjectTable<K, V> -Aborts with -iota::dynamic_field::EFieldAlreadyExists if the table already has an entry with -that key -k: K. - - -

-public fun add<K: copy, drop, store, V: store, key>(table: &mut object_table::ObjectTable<K, V>, k: K, v: V)
-
- - - -
-Implementation - - -

-public fun add<K: copy + drop + store, V: key + store>(table: &mut ObjectTable<K, V>, k: K, v: V) \{
-    ofield::add(&mut table.id, k, v);
-    table.size = table.size + 1;
-}
-
- - - -
- - - -## Function `borrow` - -Immutable borrows the value associated with the key in the table -table: &ObjectTable<K, V>. -Aborts with -iota::dynamic_field::EFieldDoesNotExist if the table does not have an entry with -that key -k: K. - - -

-public fun borrow<K: copy, drop, store, V: store, key>(table: &object_table::ObjectTable<K, V>, k: K): &V
-
- - - -
-Implementation - - -

-public fun borrow<K: copy + drop + store, V: key + store>(table: &ObjectTable<K, V>, k: K): &V \{
-    ofield::borrow(&table.id, k)
-}
-
- - - -
- - - -## Function `borrow_mut` - -Mutably borrows the value associated with the key in the table -table: &mut ObjectTable<K, V>. -Aborts with -iota::dynamic_field::EFieldDoesNotExist if the table does not have an entry with -that key -k: K. - - -

-public fun borrow_mut<K: copy, drop, store, V: store, key>(table: &mut object_table::ObjectTable<K, V>, k: K): &mut V
-
- - - -
-Implementation - - -

-public fun borrow_mut<K: copy + drop + store, V: key + store>(
-    table: &mut ObjectTable<K, V>,
-    k: K,
-): &mut V \{
-    ofield::borrow_mut(&mut table.id, k)
-}
-
- - - -
- - - -## Function `remove` - -Removes the key-value pair in the table -table: &mut ObjectTable<K, V> and returns the value. -Aborts with -iota::dynamic_field::EFieldDoesNotExist if the table does not have an entry with -that key -k: K. - - -

-public fun remove<K: copy, drop, store, V: store, key>(table: &mut object_table::ObjectTable<K, V>, k: K): V
-
- - - -
-Implementation - - -

-public fun remove<K: copy + drop + store, V: key + store>(table: &mut ObjectTable<K, V>, k: K): V \{
-    let v = ofield::remove(&mut table.id, k);
-    table.size = table.size - 1;
-    v
-}
-
- - - -
- - - -## Function `contains` - -Returns true iff there is a value associated with the key -k: K in table - -table: &ObjectTable<K, V> - - -

-public fun contains<K: copy, drop, store, V: store, key>(table: &object_table::ObjectTable<K, V>, k: K): bool
-
- - - -
-Implementation - - -

-public fun contains<K: copy + drop + store, V: key + store>(table: &ObjectTable<K, V>, k: K): bool \{
-    ofield::exists_<K>(&table.id, k)
-}
-
- - - -
- - - -## Function `length` - -Returns the size of the table, the number of key-value pairs - - -

-public fun length<K: copy, drop, store, V: store, key>(table: &object_table::ObjectTable<K, V>): u64
-
- - - -
-Implementation - - -

-public fun length<K: copy + drop + store, V: key + store>(table: &ObjectTable<K, V>): u64 \{
-    table.size
-}
-
- - - -
- - - -## Function `is_empty` - -Returns true iff the table is empty (if -length returns -0) - - -

-public fun is_empty<K: copy, drop, store, V: store, key>(table: &object_table::ObjectTable<K, V>): bool
-
- - - -
-Implementation - - -

-public fun is_empty<K: copy + drop + store, V: key + store>(table: &ObjectTable<K, V>): bool \{
-    table.size == 0
-}
-
- - - -
- - - -## Function `destroy_empty` - -Destroys an empty table -Aborts with -ETableNotEmpty if the table still contains values - - -

-public fun destroy_empty<K: copy, drop, store, V: store, key>(table: object_table::ObjectTable<K, V>)
-
- - - -
-Implementation - - -

-public fun destroy_empty<K: copy + drop + store, V: key + store>(table: ObjectTable<K, V>) \{
-    let ObjectTable \{ id, size } = table;
-    assert!(size == 0, ETableNotEmpty);
-    id.delete()
-}
-
- - - -
- - - -## Function `value_id` - -Returns the ID of the object associated with the key if the table has an entry with key -k: K -Returns none otherwise - - -

-public fun value_id<K: copy, drop, store, V: store, key>(table: &object_table::ObjectTable<K, V>, k: K): option::Option<object::ID>
-
- - - -
-Implementation - - -

-public fun value_id<K: copy + drop + store, V: key + store>(
-    table: &ObjectTable<K, V>,
-    k: K,
-): Option<ID> \{
-    ofield::id(&table.id, k)
-}
-
- - - -
diff --git a/crates/iota-framework/docs/iota-framework/package.mdx b/crates/iota-framework/docs/iota-framework/package.mdx deleted file mode 100644 index 7018193798c..00000000000 --- a/crates/iota-framework/docs/iota-framework/package.mdx +++ /dev/null @@ -1,1084 +0,0 @@ ---- -title: Module `0x2::package` ---- -import Link from '@docusaurus/Link'; - - -Functions for operating on Move packages from within Move: -- Creating proof-of-publish objects from one-time witnesses -- Administering package upgrades through upgrade policies. - - -- [Resource `Publisher`](#0x2_package_Publisher) -- [Resource `UpgradeCap`](#0x2_package_UpgradeCap) -- [Struct `UpgradeTicket`](#0x2_package_UpgradeTicket) -- [Struct `UpgradeReceipt`](#0x2_package_UpgradeReceipt) -- [Constants](#@Constants_0) -- [Function `claim`](#0x2_package_claim) -- [Function `claim_and_keep`](#0x2_package_claim_and_keep) -- [Function `burn_publisher`](#0x2_package_burn_publisher) -- [Function `from_package`](#0x2_package_from_package) -- [Function `from_module`](#0x2_package_from_module) -- [Function `published_module`](#0x2_package_published_module) -- [Function `published_package`](#0x2_package_published_package) -- [Function `upgrade_package`](#0x2_package_upgrade_package) -- [Function `version`](#0x2_package_version) -- [Function `upgrade_policy`](#0x2_package_upgrade_policy) -- [Function `ticket_package`](#0x2_package_ticket_package) -- [Function `ticket_policy`](#0x2_package_ticket_policy) -- [Function `receipt_cap`](#0x2_package_receipt_cap) -- [Function `receipt_package`](#0x2_package_receipt_package) -- [Function `ticket_digest`](#0x2_package_ticket_digest) -- [Function `compatible_policy`](#0x2_package_compatible_policy) -- [Function `additive_policy`](#0x2_package_additive_policy) -- [Function `dep_only_policy`](#0x2_package_dep_only_policy) -- [Function `only_additive_upgrades`](#0x2_package_only_additive_upgrades) -- [Function `only_dep_upgrades`](#0x2_package_only_dep_upgrades) -- [Function `make_immutable`](#0x2_package_make_immutable) -- [Function `authorize_upgrade`](#0x2_package_authorize_upgrade) -- [Function `commit_upgrade`](#0x2_package_commit_upgrade) -- [Function `restrict`](#0x2_package_restrict) - - -

-use 0x1::ascii;
-use 0x1::type_name;
-use 0x2::object;
-use 0x2::transfer;
-use 0x2::tx_context;
-use 0x2::types;
-
- - - - - -## Resource `Publisher` - -This type can only be created in the transaction that -generates a module, by consuming its one-time witness, so it -can be used to identify the address that published the package -a type originated from. - - -

-struct Publisher has store, key
-
- - - -
-Fields - - -
-
- -id: object::UID -
-
- -
-
- -package: ascii::String -
-
- -
-
- -module_name: ascii::String -
-
- -
-
- - -
- - - -## Resource `UpgradeCap` - -Capability controlling the ability to upgrade a package. - - -

-struct UpgradeCap has store, key
-
- - - -
-Fields - - -
-
- -id: object::UID -
-
- -
-
- -package: object::ID -
-
- (Mutable) ID of the package that can be upgraded. -
-
- -version: u64 -
-
- (Mutable) The number of upgrades that have been applied - successively to the original package. Initially 0. -
-
- -policy: u8 -
-
- What kind of upgrades are allowed. -
-
- - -
- - - -## Struct `UpgradeTicket` - -Permission to perform a particular upgrade (for a fixed version of -the package, bytecode to upgrade with and transitive dependencies to -depend against). - -An -UpgradeCap can only issue one ticket at a time, to prevent races -between concurrent updates or a change in its upgrade policy after -isiotang a ticket, so the ticket is a "Hot Potato" to preserve forward -progress. - - -

-struct UpgradeTicket
-
- - - -
-Fields - - -
-
- -cap: object::ID -
-
- (Immutable) ID of the -UpgradeCap this originated from. -
-
- -package: object::ID -
-
- (Immutable) ID of the package that can be upgraded. -
-
- -policy: u8 -
-
- (Immutable) The policy regarding what kind of upgrade this ticket - permits. -
-
- -digest: vector<u8> -
-
- (Immutable) SHA256 digest of the bytecode and transitive - dependencies that will be used in the upgrade. -
-
- - -
- - - -## Struct `UpgradeReceipt` - -Issued as a result of a successful upgrade, containing the -information to be used to update the -UpgradeCap. This is a "Hot -Potato" to ensure that it is used to update its -UpgradeCap before -the end of the transaction that performed the upgrade. - - -

-struct UpgradeReceipt
-
- - - -
-Fields - - -
-
- -cap: object::ID -
-
- (Immutable) ID of the -UpgradeCap this originated from. -
-
- -package: object::ID -
-
- (Immutable) ID of the package after it was upgraded. -
-
- - -
- - - -## Constants - - - - -Add new functions or types, or change dependencies, existing -functions can't change. - - -

-const ADDITIVE: u8 = 128;
-
- - - - - -Update any part of the package (function implementations, add new -functions or types, change dependencies) - - -

-const COMPATIBLE: u8 = 0;
-
- - - - - -Only be able to change dependencies. - - -

-const DEP_ONLY: u8 = 192;
-
- - - - - -This -UpgradeCap has already authorized a pending upgrade. - - -

-const EAlreadyAuthorized: u64 = 2;
-
- - - - - -This -UpgradeCap has not authorized an upgrade. - - -

-const ENotAuthorized: u64 = 3;
-
- - - - - -Tried to create a -Publisher using a type that isn't a -one-time witness. - - -

-const ENotOneTimeWitness: u64 = 0;
-
- - - - - -Tried to set a less restrictive policy than currently in place. - - -

-const ETooPermissive: u64 = 1;
-
- - - - - -Trying to commit an upgrade to the wrong -UpgradeCap. - - -

-const EWrongUpgradeCap: u64 = 4;
-
- - - - - -## Function `claim` - -Claim a Publisher object. -Requires a One-Time-Witness to prove ownership. Due to this -constraint there can be only one Publisher object per module -but multiple per package (!). - - -

-public fun claim<OTW: drop>(otw: OTW, ctx: &mut tx_context::TxContext): package::Publisher
-
- - - -
-Implementation - - -

-public fun claim<OTW: drop>(otw: OTW, ctx: &mut TxContext): Publisher \{
-    assert!(types::is_one_time_witness(&otw), ENotOneTimeWitness);
-
-    let tyname = type_name::get_with_original_ids<OTW>();
-
-    Publisher \{
-        id: object::new(ctx),
-        package: tyname.get_address(),
-        module_name: tyname.get_module(),
-    }
-}
-
- - - -
- - - -## Function `claim_and_keep` - -Claim a Publisher object and send it to transaction sender. -Since this function can only be called in the module initializer, -the sender is the publisher. - - -

-public fun claim_and_keep<OTW: drop>(otw: OTW, ctx: &mut tx_context::TxContext)
-
- - - -
-Implementation - - -

-public fun claim_and_keep<OTW: drop>(otw: OTW, ctx: &mut TxContext) \{
-    iota::transfer::public_transfer(claim(otw, ctx), ctx.sender())
-}
-
- - - -
- - - -## Function `burn_publisher` - -Destroy a Publisher object effectively removing all privileges -associated with it. - - -

-public fun burn_publisher(self: package::Publisher)
-
- - - -
-Implementation - - -

-public fun burn_publisher(self: Publisher) \{
-    let Publisher \{ id, package: _, module_name: _ } = self;
-    id.delete();
-}
-
- - - -
- - - -## Function `from_package` - -Check whether type belongs to the same package as the publisher object. - - -

-public fun from_package<T>(self: &package::Publisher): bool
-
- - - -
-Implementation - - -

-public fun from_package<T>(self: &Publisher): bool \{
-    type_name::get_with_original_ids<T>().get_address() == self.package
-}
-
- - - -
- - - -## Function `from_module` - -Check whether a type belongs to the same module as the publisher object. - - -

-public fun from_module<T>(self: &package::Publisher): bool
-
- - - -
-Implementation - - -

-public fun from_module<T>(self: &Publisher): bool \{
-    let tyname = type_name::get_with_original_ids<T>();
-
-    (tyname.get_address() == self.package) && (tyname.get_module() == self.module_name)
-}
-
- - - -
- - - -## Function `published_module` - -Read the name of the module. - - -

-public fun published_module(self: &package::Publisher): &ascii::String
-
- - - -
-Implementation - - -

-public fun published_module(self: &Publisher): &String \{
-    &self.module_name
-}
-
- - - -
- - - -## Function `published_package` - -Read the package address string. - - -

-public fun published_package(self: &package::Publisher): &ascii::String
-
- - - -
-Implementation - - -

-public fun published_package(self: &Publisher): &String \{
-    &self.package
-}
-
- - - -
- - - -## Function `upgrade_package` - -The ID of the package that this cap authorizes upgrades for. -Can be -0x0 if the cap cannot currently authorize an upgrade -because there is already a pending upgrade in the transaction. -Otherwise guaranteed to be the latest version of any given -package. - - -

-public fun upgrade_package(cap: &package::UpgradeCap): object::ID
-
- - - -
-Implementation - - -

-public fun upgrade_package(cap: &UpgradeCap): ID \{
-    cap.package
-}
-
- - - -
- - - -## Function `version` - -The most recent version of the package, increments by one for each -successfully applied upgrade. - - -

-public fun version(cap: &package::UpgradeCap): u64
-
- - - -
-Implementation - - -

-public fun version(cap: &UpgradeCap): u64 \{
-    cap.version
-}
-
- - - -
- - - -## Function `upgrade_policy` - -The most permissive kind of upgrade currently supported by this - -cap. - - -

-public fun upgrade_policy(cap: &package::UpgradeCap): u8
-
- - - -
-Implementation - - -

-public fun upgrade_policy(cap: &UpgradeCap): u8 \{
-    cap.policy
-}
-
- - - -
- - - -## Function `ticket_package` - -The package that this ticket is authorized to upgrade - - -

-public fun ticket_package(ticket: &package::UpgradeTicket): object::ID
-
- - - -
-Implementation - - -

-public fun ticket_package(ticket: &UpgradeTicket): ID \{
-    ticket.package
-}
-
- - - -
- - - -## Function `ticket_policy` - -The kind of upgrade that this ticket authorizes. - - -

-public fun ticket_policy(ticket: &package::UpgradeTicket): u8
-
- - - -
-Implementation - - -

-public fun ticket_policy(ticket: &UpgradeTicket): u8 \{
-    ticket.policy
-}
-
- - - -
- - - -## Function `receipt_cap` - -ID of the -UpgradeCap that this -receipt should be used to -update. - - -

-public fun receipt_cap(receipt: &package::UpgradeReceipt): object::ID
-
- - - -
-Implementation - - -

-public fun receipt_cap(receipt: &UpgradeReceipt): ID \{
-    receipt.cap
-}
-
- - - -
- - - -## Function `receipt_package` - -ID of the package that was upgraded to: the latest version of -the package, as of the upgrade represented by this -receipt. - - -

-public fun receipt_package(receipt: &package::UpgradeReceipt): object::ID
-
- - - -
-Implementation - - -

-public fun receipt_package(receipt: &UpgradeReceipt): ID \{
-    receipt.package
-}
-
- - - -
- - - -## Function `ticket_digest` - -A hash of the package contents for the new version of the -package. This ticket only authorizes an upgrade to a package -that matches this digest. A package's contents are identified -by two things: - -- modules: [[u8]] a list of the package's module contents -- deps: [[u8; 32]] a list of 32 byte ObjectIDs of the -package's transitive dependencies - -A package's digest is calculated as: - -sha3_256(sort(modules ++ deps)) - - -

-public fun ticket_digest(ticket: &package::UpgradeTicket): &vector<u8>
-
- - - -
-Implementation - - -

-public fun ticket_digest(ticket: &UpgradeTicket): &vector<u8> \{
-    &ticket.digest
-}
-
- - - -
- - - -## Function `compatible_policy` - -Expose the constants representing various upgrade policies - - -

-public fun compatible_policy(): u8
-
- - - -
-Implementation - - -

-public fun compatible_policy(): u8 \{ COMPATIBLE }
-
- - - -
- - - -## Function `additive_policy` - - - -

-public fun additive_policy(): u8
-
- - - -
-Implementation - - -

-public fun additive_policy(): u8 \{ ADDITIVE }
-
- - - -
- - - -## Function `dep_only_policy` - - - -

-public fun dep_only_policy(): u8
-
- - - -
-Implementation - - -

-public fun dep_only_policy(): u8 \{ DEP_ONLY }
-
- - - -
- - - -## Function `only_additive_upgrades` - -Restrict upgrades through this upgrade -cap to just add code, or -change dependencies. - - -

-public entry fun only_additive_upgrades(cap: &mut package::UpgradeCap)
-
- - - -
-Implementation - - -

-public entry fun only_additive_upgrades(cap: &mut UpgradeCap) \{
-    cap.restrict(ADDITIVE)
-}
-
- - - -
- - - -## Function `only_dep_upgrades` - -Restrict upgrades through this upgrade -cap to just change -dependencies. - - -

-public entry fun only_dep_upgrades(cap: &mut package::UpgradeCap)
-
- - - -
-Implementation - - -

-public entry fun only_dep_upgrades(cap: &mut UpgradeCap) \{
-    cap.restrict(DEP_ONLY)
-}
-
- - - -
- - - -## Function `make_immutable` - -Discard the -UpgradeCap to make a package immutable. - - -

-public entry fun make_immutable(cap: package::UpgradeCap)
-
- - - -
-Implementation - - -

-public entry fun make_immutable(cap: UpgradeCap) \{
-    let UpgradeCap \{ id, package: _, version: _, policy: _ } = cap;
-    id.delete();
-}
-
- - - -
- - - -## Function `authorize_upgrade` - -Issue a ticket authorizing an upgrade to a particular new bytecode -(identified by its digest). A ticket will only be issued if one has -not already been issued, and if the -policy requested is at least as -restrictive as the policy set out by the -cap. - -The -digest supplied and the -policy will both be checked by -validators when running the upgrade. I.e. the bytecode supplied in -the upgrade must have a matching digest, and the changes relative to -the parent package must be compatible with the policy in the ticket -for the upgrade to succeed. - - -

-public fun authorize_upgrade(cap: &mut package::UpgradeCap, policy: u8, digest: vector<u8>): package::UpgradeTicket
-
- - - -
-Implementation - - -

-public fun authorize_upgrade(
-    cap: &mut UpgradeCap,
-    policy: u8,
-    digest: vector<u8>
-): UpgradeTicket \{
-    let id_zero = @0x0.to_id();
-    assert!(cap.package != id_zero, EAlreadyAuthorized);
-    assert!(policy >= cap.policy, ETooPermissive);
-
-    let package = cap.package;
-    cap.package = id_zero;
-
-    UpgradeTicket \{
-        cap: object::id(cap),
-        package,
-        policy,
-        digest,
-    }
-}
-
- - - -
- - - -## Function `commit_upgrade` - -Consume an -UpgradeReceipt to update its -UpgradeCap, finalizing -the upgrade. - - -

-public fun commit_upgrade(cap: &mut package::UpgradeCap, receipt: package::UpgradeReceipt)
-
- - - -
-Implementation - - -

-public fun commit_upgrade(
-    cap: &mut UpgradeCap,
-    receipt: UpgradeReceipt,
-) \{
-    let UpgradeReceipt \{ cap: cap_id, package } = receipt;
-
-    assert!(object::id(cap) == cap_id, EWrongUpgradeCap);
-    assert!(cap.package.to_address() == @0x0, ENotAuthorized);
-
-    cap.package = package;
-    cap.version = cap.version + 1;
-}
-
- - - -
- - - -## Function `restrict` - - - -

-fun restrict(cap: &mut package::UpgradeCap, policy: u8)
-
- - - -
-Implementation - - -

-fun restrict(cap: &mut UpgradeCap, policy: u8) \{
-    assert!(cap.policy <= policy, ETooPermissive);
-    cap.policy = policy;
-}
-
- - - -
diff --git a/crates/iota-framework/docs/iota-framework/pay.mdx b/crates/iota-framework/docs/iota-framework/pay.mdx deleted file mode 100644 index 799e5df672c..00000000000 --- a/crates/iota-framework/docs/iota-framework/pay.mdx +++ /dev/null @@ -1,319 +0,0 @@ ---- -title: Module `0x2::pay` ---- -import Link from '@docusaurus/Link'; - - -This module provides handy functionality for wallets and -iota::Coin management. - - -- [Constants](#@Constants_0) -- [Function `keep`](#0x2_pay_keep) -- [Function `split`](#0x2_pay_split) -- [Function `split_vec`](#0x2_pay_split_vec) -- [Function `split_and_transfer`](#0x2_pay_split_and_transfer) -- [Function `divide_and_keep`](#0x2_pay_divide_and_keep) -- [Function `join`](#0x2_pay_join) -- [Function `join_vec`](#0x2_pay_join_vec) -- [Function `join_vec_and_transfer`](#0x2_pay_join_vec_and_transfer) - - -

-use 0x2::coin;
-use 0x2::transfer;
-use 0x2::tx_context;
-
- - - - - -## Constants - - - - -For when empty vector is supplied into join function. - - -

-const ENoCoins: u64 = 0;
-
- - - - - -## Function `keep` - -Transfer -c to the sender of the current transaction - - -

-public fun keep<T>(c: coin::Coin<T>, ctx: &tx_context::TxContext)
-
- - - -
-Implementation - - -

-public fun keep<T>(c: Coin<T>, ctx: &TxContext) \{
-    transfer::public_transfer(c, ctx.sender())
-}
-
- - - -
- - - -## Function `split` - -Split coin -self to two coins, one with balance -split_amount, -and the remaining balance is left is -self. - - -

-public entry fun split<T>(coin: &mut coin::Coin<T>, split_amount: u64, ctx: &mut tx_context::TxContext)
-
- - - -
-Implementation - - -

-public entry fun split<T>(
-    coin: &mut Coin<T>, split_amount: u64, ctx: &mut TxContext
-) \{
-    keep(coin.split(split_amount, ctx), ctx)
-}
-
- - - -
- - - -## Function `split_vec` - -Split coin -self into multiple coins, each with balance specified -in -split_amounts. Remaining balance is left in -self. - - -

-public entry fun split_vec<T>(self: &mut coin::Coin<T>, split_amounts: vector<u64>, ctx: &mut tx_context::TxContext)
-
- - - -
-Implementation - - -

-public entry fun split_vec<T>(
-    self: &mut Coin<T>, split_amounts: vector<u64>, ctx: &mut TxContext
-) \{
-    let (mut i, len) = (0, split_amounts.length());
-    while (i < len) \{
-        split(self, split_amounts[i], ctx);
-        i = i + 1;
-    };
-}
-
- - - -
- - - -## Function `split_and_transfer` - -Send -amount units of -c to -recipient -Aborts with -EVALUE if -amount is greater than or equal to -amount - - -

-public entry fun split_and_transfer<T>(c: &mut coin::Coin<T>, amount: u64, recipient: address, ctx: &mut tx_context::TxContext)
-
- - - -
-Implementation - - -

-public entry fun split_and_transfer<T>(
-    c: &mut Coin<T>, amount: u64, recipient: address, ctx: &mut TxContext
-) \{
-    transfer::public_transfer(c.split(amount, ctx), recipient)
-}
-
- - - -
- - - -## Function `divide_and_keep` - -Divide coin -self into -n - 1 coins with equal balances. If the balance is -not evenly divisible by -n, the remainder is left in -self. - - -

-public entry fun divide_and_keep<T>(self: &mut coin::Coin<T>, n: u64, ctx: &mut tx_context::TxContext)
-
- - - -
-Implementation - - -

-public entry fun divide_and_keep<T>(
-    self: &mut Coin<T>, n: u64, ctx: &mut TxContext
-) \{
-    let mut vec: vector<Coin<T>> = self.divide_into_n(n, ctx);
-    let (mut i, len) = (0, vec.length());
-    while (i < len) \{
-        transfer::public_transfer(vec.pop_back(), ctx.sender());
-        i = i + 1;
-    };
-    vec.destroy_empty();
-}
-
- - - -
- - - -## Function `join` - -Join -coin into -self. Re-exports -coin::join function. -Deprecated: you should call -coin.join(other) directly. - - -

-public entry fun join<T>(self: &mut coin::Coin<T>, coin: coin::Coin<T>)
-
- - - -
-Implementation - - -

-public entry fun join<T>(self: &mut Coin<T>, coin: Coin<T>) \{
-    self.join(coin)
-}
-
- - - -
- - - -## Function `join_vec` - -Join everything in -coins with -self - - -

-public entry fun join_vec<T>(self: &mut coin::Coin<T>, coins: vector<coin::Coin<T>>)
-
- - - -
-Implementation - - -

-public entry fun join_vec<T>(self: &mut Coin<T>, mut coins: vector<Coin<T>>) \{
-    let (mut i, len) = (0, coins.length());
-    while (i < len) \{
-        let coin = coins.pop_back();
-        self.join(coin);
-        i = i + 1
-    };
-    // safe because we've drained the vector
-    coins.destroy_empty()
-}
-
- - - -
- - - -## Function `join_vec_and_transfer` - -Join a vector of -Coin into a single object and transfer it to -receiver. - - -

-public entry fun join_vec_and_transfer<T>(coins: vector<coin::Coin<T>>, receiver: address)
-
- - - -
-Implementation - - -

-public entry fun join_vec_and_transfer<T>(mut coins: vector<Coin<T>>, receiver: address) \{
-    assert!(coins.length() > 0, ENoCoins);
-
-    let mut self = coins.pop_back();
-    join_vec(&mut self, coins);
-    transfer::public_transfer(self, receiver)
-}
-
- - - -
diff --git a/crates/iota-framework/docs/iota-framework/poseidon.mdx b/crates/iota-framework/docs/iota-framework/poseidon.mdx deleted file mode 100644 index 160ac646944..00000000000 --- a/crates/iota-framework/docs/iota-framework/poseidon.mdx +++ /dev/null @@ -1,125 +0,0 @@ ---- -title: Module `0x2::poseidon` ---- -import Link from '@docusaurus/Link'; - - -Module which defines instances of the poseidon hash functions. - - -- [Constants](#@Constants_0) -- [Function `poseidon_bn254`](#0x2_poseidon_poseidon_bn254) -- [Function `poseidon_bn254_internal`](#0x2_poseidon_poseidon_bn254_internal) - - -

-use 0x2::bcs;
-
- - - - - -## Constants - - - - -The field size for BN254 curve. - - -

-const BN254_MAX: u256 = 21888242871839275222246405745257275088548364400416034343698204186575808495617;
-
- - - - - -Error if an empty vector is passed as input. - - -

-const EEmptyInput: u64 = 1;
-
- - - - - -Error if any of the inputs are larger than or equal to the BN254 field size. - - -

-const ENonCanonicalInput: u64 = 0;
-
- - - - - -## Function `poseidon_bn254` - -@param data: Vector of BN254 field elements to hash. - -Hash the inputs using poseidon_bn254 and returns a BN254 field element. - -Each element has to be a BN254 field element in canonical representation so it must be smaller than the BN254 -scalar field size which is 21888242871839275222246405745257275088548364400416034343698204186575808495617. - - -

-public fun poseidon_bn254(data: &vector<u256>): u256
-
- - - -
-Implementation - - -

-public fun poseidon_bn254(data: &vector<u256>): u256 \{
-    let (mut i, mut b, l) = (0, vector[], data.length());
-    assert!(l > 0, EEmptyInput);
-    while (i < l) \{
-        let field_element = &data[i];
-        assert!(*field_element < BN254_MAX, ENonCanonicalInput);
-        b.push_back(bcs::to_bytes(&data[i]));
-        i = i + 1;
-    };
-    let binary_output = poseidon_bn254_internal(&b);
-    bcs::new(binary_output).peel_u256()
-}
-
- - - -
- - - -## Function `poseidon_bn254_internal` - -@param data: Vector of BN254 field elements in little-endian representation. - -Hash the inputs using poseidon_bn254 and returns a BN254 field element in little-endian representation. - - -

-fun poseidon_bn254_internal(data: &vector<vector<u8>>): vector<u8>
-
- - - -
-Implementation - - -

-native fun poseidon_bn254_internal(data: &vector<vector<u8>>): vector<u8>;
-
- - - -
diff --git a/crates/iota-framework/docs/iota-framework/priority_queue.mdx b/crates/iota-framework/docs/iota-framework/priority_queue.mdx deleted file mode 100644 index ff90a35aa9e..00000000000 --- a/crates/iota-framework/docs/iota-framework/priority_queue.mdx +++ /dev/null @@ -1,395 +0,0 @@ ---- -title: Module `0x2::priority_queue` ---- -import Link from '@docusaurus/Link'; - - -Priority queue implemented using a max heap. - - -- [Struct `PriorityQueue`](#0x2_priority_queue_PriorityQueue) -- [Struct `Entry`](#0x2_priority_queue_Entry) -- [Constants](#@Constants_0) -- [Function `new`](#0x2_priority_queue_new) -- [Function `pop_max`](#0x2_priority_queue_pop_max) -- [Function `insert`](#0x2_priority_queue_insert) -- [Function `new_entry`](#0x2_priority_queue_new_entry) -- [Function `create_entries`](#0x2_priority_queue_create_entries) -- [Function `restore_heap_recursive`](#0x2_priority_queue_restore_heap_recursive) -- [Function `max_heapify_recursive`](#0x2_priority_queue_max_heapify_recursive) -- [Function `priorities`](#0x2_priority_queue_priorities) - - -

-use 0x1::vector;
-
- - - - - -## Struct `PriorityQueue` - -Struct representing a priority queue. The -entries vector represents a max -heap structure, where entries[0] is the root, entries[1] and entries[2] are the -left child and right child of the root, etc. More generally, the children of -entries[i] are at at i * 2 + 1 and i * 2 + 2. The max heap should have the invariant -that the parent node's priority is always higher than its child nodes' priorities. - - -

-struct PriorityQueue<T: drop> has drop, store
-
- - - -
-Fields - - -
-
- -entries: vector<priority_queue::Entry<T>> -
-
- -
-
- - -
- - - -## Struct `Entry` - - - -

-struct Entry<T: drop> has drop, store
-
- - - -
-Fields - - -
-
- -priority: u64 -
-
- -
-
- -value: T -
-
- -
-
- - -
- - - -## Constants - - - - -For when heap is empty and there's no data to pop. - - -

-const EPopFromEmptyHeap: u64 = 0;
-
- - - - - -## Function `new` - -Create a new priority queue from the input entry vectors. - - -

-public fun new<T: drop>(entries: vector<priority_queue::Entry<T>>): priority_queue::PriorityQueue<T>
-
- - - -
-Implementation - - -

-public fun new<T: drop>(mut entries: vector<Entry<T>>) : PriorityQueue<T> \{
-    let len = entries.length();
-    let mut i = len / 2;
-    // Max heapify from the first node that is a parent (node at len / 2).
-    while (i > 0) \{
-        i = i - 1;
-        max_heapify_recursive(&mut entries, len, i);
-    };
-    PriorityQueue \{ entries }
-}
-
- - - -
- - - -## Function `pop_max` - -Pop the entry with the highest priority value. - - -

-public fun pop_max<T: drop>(pq: &mut priority_queue::PriorityQueue<T>): (u64, T)
-
- - - -
-Implementation - - -

-public fun pop_max<T: drop>(pq: &mut PriorityQueue<T>) : (u64, T) \{
-    let len = pq.entries.length();
-    assert!(len > 0, EPopFromEmptyHeap);
-    // Swap the max element with the last element in the entries and remove the max element.
-    let Entry \{ priority, value } = pq.entries.swap_remove(0);
-    // Now the max heap property has been violated at the root node, but nowhere else
-    // so we call max heapify on the root node.
-    max_heapify_recursive(&mut pq.entries, len - 1, 0);
-    (priority, value)
-}
-
- - - -
- - - -## Function `insert` - -Insert a new entry into the queue. - - -

-public fun insert<T: drop>(pq: &mut priority_queue::PriorityQueue<T>, priority: u64, value: T)
-
- - - -
-Implementation - - -

-public fun insert<T: drop>(pq: &mut PriorityQueue<T>, priority: u64, value: T) \{
-    pq.entries.push_back(Entry \{ priority, value});
-    let index = pq.entries.length() - 1;
-    restore_heap_recursive(&mut pq.entries, index);
-}
-
- - - -
- - - -## Function `new_entry` - - - -

-public fun new_entry<T: drop>(priority: u64, value: T): priority_queue::Entry<T>
-
- - - -
-Implementation - - -

-public fun new_entry<T: drop>(priority: u64, value: T): Entry<T> \{
-    Entry \{ priority, value }
-}
-
- - - -
- - - -## Function `create_entries` - - - -

-public fun create_entries<T: drop>(p: vector<u64>, v: vector<T>): vector<priority_queue::Entry<T>>
-
- - - -
-Implementation - - -

-public fun create_entries<T: drop>(mut p: vector<u64>, mut v: vector<T>): vector<Entry<T>> \{
-    let len = p.length();
-    assert!(v.length() == len, 0);
-    let mut res = vector[];
-    let mut i = 0;
-    while (i < len) \{
-        let priority = p.remove(0);
-        let value = v.remove(0);
-        res.push_back(Entry \{ priority, value });
-        i = i + 1;
-    };
-    res
-}
-
- - - -
- - - -## Function `restore_heap_recursive` - - - -

-fun restore_heap_recursive<T: drop>(v: &mut vector<priority_queue::Entry<T>>, i: u64)
-
- - - -
-Implementation - - -

-fun restore_heap_recursive<T: drop>(v: &mut vector<Entry<T>>, i: u64) \{
-    if (i == 0) \{
-        return
-    };
-    let parent = (i - 1) / 2;
-
-    // If new elem is greater than its parent, swap them and recursively
-    // do the restoration upwards.
-    if (*&v[i].priority > *&v[parent].priority) \{
-        v.swap(i, parent);
-        restore_heap_recursive(v, parent);
-    }
-}
-
- - - -
- - - -## Function `max_heapify_recursive` - -Max heapify the subtree whose root is at index -i. That means after this function -finishes, the subtree should have the property that the parent node has higher priority -than both child nodes. -This function assumes that all the other nodes in the subtree (nodes other than the root) -do satisfy the max heap property. - - -

-fun max_heapify_recursive<T: drop>(v: &mut vector<priority_queue::Entry<T>>, len: u64, i: u64)
-
- - - -
-Implementation - - -

-fun max_heapify_recursive<T: drop>(v: &mut vector<Entry<T>>, len: u64, i: u64) \{
-    if (len == 0) \{
-        return
-    };
-    assert!(i < len, 1);
-    let left = i * 2 + 1;
-    let right = left + 1;
-    let mut max = i;
-    // Find the node with highest priority among node `i` and its two children.
-    if (left < len && *&v[left].priority > *&v[max].priority) \{
-        max = left;
-    };
-    if (right < len && *&v[right].priority > *&v[max].priority) \{
-        max = right;
-    };
-    // If the parent node (node `i`) doesn't have the highest priority, we swap the parent with the
-    // max priority node.
-    if (max != i) \{
-        v.swap(max, i);
-        // After the swap, we have restored the property at node `i` but now the max heap property
-        // may be violated at node `max` since this node now has a new value. So we need to now
-        // max heapify the subtree rooted at node `max`.
-        max_heapify_recursive(v, len, max);
-    }
-}
-
- - - -
- - - -## Function `priorities` - - - -

-public fun priorities<T: drop>(pq: &priority_queue::PriorityQueue<T>): vector<u64>
-
- - - -
-Implementation - - -

-public fun priorities<T: drop>(pq: &PriorityQueue<T>): vector<u64> \{
-    let mut res = vector[];
-    let mut i = 0;
-    while (i < pq.entries.length()) \{
-        res.push_back(pq.entries[i].priority);
-        i = i +1;
-    };
-    res
-}
-
- - - -
diff --git a/crates/iota-framework/docs/iota-framework/prover.mdx b/crates/iota-framework/docs/iota-framework/prover.mdx deleted file mode 100644 index 2ada86c1a96..00000000000 --- a/crates/iota-framework/docs/iota-framework/prover.mdx +++ /dev/null @@ -1,12 +0,0 @@ ---- -title: Module `0x2::prover` ---- -import Link from '@docusaurus/Link'; - - - - - - -

-
diff --git a/crates/iota-framework/docs/iota-framework/random.mdx b/crates/iota-framework/docs/iota-framework/random.mdx deleted file mode 100644 index 3ad6ed1edc6..00000000000 --- a/crates/iota-framework/docs/iota-framework/random.mdx +++ /dev/null @@ -1,996 +0,0 @@ ---- -title: Module `0x2::random` ---- -import Link from '@docusaurus/Link'; - - -This module provides functionality for generating secure randomness. - - -- [Resource `Random`](#0x2_random_Random) -- [Struct `RandomInner`](#0x2_random_RandomInner) -- [Struct `RandomGenerator`](#0x2_random_RandomGenerator) -- [Constants](#@Constants_0) -- [Function `create`](#0x2_random_create) -- [Function `load_inner_mut`](#0x2_random_load_inner_mut) -- [Function `load_inner`](#0x2_random_load_inner) -- [Function `update_randomness_state`](#0x2_random_update_randomness_state) -- [Function `new_generator`](#0x2_random_new_generator) -- [Function `derive_next_block`](#0x2_random_derive_next_block) -- [Function `fill_buffer`](#0x2_random_fill_buffer) -- [Function `generate_bytes`](#0x2_random_generate_bytes) -- [Function `u256_from_bytes`](#0x2_random_u256_from_bytes) -- [Function `generate_u256`](#0x2_random_generate_u256) -- [Function `generate_u128`](#0x2_random_generate_u128) -- [Function `generate_u64`](#0x2_random_generate_u64) -- [Function `generate_u32`](#0x2_random_generate_u32) -- [Function `generate_u16`](#0x2_random_generate_u16) -- [Function `generate_u8`](#0x2_random_generate_u8) -- [Function `generate_bool`](#0x2_random_generate_bool) -- [Function `u128_in_range`](#0x2_random_u128_in_range) -- [Function `generate_u128_in_range`](#0x2_random_generate_u128_in_range) -- [Function `generate_u64_in_range`](#0x2_random_generate_u64_in_range) -- [Function `generate_u32_in_range`](#0x2_random_generate_u32_in_range) -- [Function `generate_u16_in_range`](#0x2_random_generate_u16_in_range) -- [Function `generate_u8_in_range`](#0x2_random_generate_u8_in_range) -- [Function `shuffle`](#0x2_random_shuffle) - - -

-use 0x1::bcs;
-use 0x1::vector;
-use 0x2::address;
-use 0x2::hmac;
-use 0x2::object;
-use 0x2::transfer;
-use 0x2::tx_context;
-use 0x2::versioned;
-
- - - - - -## Resource `Random` - -Singleton shared object which stores the global randomness state. -The actual state is stored in a versioned inner field. - - -

-struct Random has key
-
- - - -
-Fields - - -
-
- -id: object::UID -
-
- -
-
- -inner: versioned::Versioned -
-
- -
-
- - -
- - - -## Struct `RandomInner` - - - -

-struct RandomInner has store
-
- - - -
-Fields - - -
-
- -version: u64 -
-
- -
-
- -epoch: u64 -
-
- -
-
- -randomness_round: u64 -
-
- -
-
- -random_bytes: vector<u8> -
-
- -
-
- - -
- - - -## Struct `RandomGenerator` - -Unique randomness generator, derived from the global randomness. - - -

-struct RandomGenerator has drop
-
- - - -
-Fields - - -
-
- -seed: vector<u8> -
-
- -
-
- -counter: u16 -
-
- -
-
- -buffer: vector<u8> -
-
- -
-
- - -
- - - -## Constants - - - - - - -

-const ENotSystemAddress: u64 = 0;
-
- - - - - - - -

-const EWrongInnerVersion: u64 = 1;
-
- - - - - - - -

-const CURRENT_VERSION: u64 = 1;
-
- - - - - - - -

-const EInvalidLength: u64 = 4;
-
- - - - - - - -

-const EInvalidRandomnessUpdate: u64 = 2;
-
- - - - - - - -

-const EInvalidRange: u64 = 3;
-
- - - - - - - -

-const RAND_OUTPUT_LEN: u16 = 32;
-
- - - - - - - -

-const U16_MAX: u64 = 65535;
-
- - - - - -## Function `create` - -Create and share the Random object. This function is called exactly once, when -the Random object is first created. -Can only be called by genesis or change_epoch transactions. - - -

-fun create(ctx: &mut tx_context::TxContext)
-
- - - -
-Implementation - - -

-fun create(ctx: &mut TxContext) \{
-    assert!(ctx.sender() == @0x0, ENotSystemAddress);
-
-    let version = CURRENT_VERSION;
-
-    let inner = RandomInner \{
-        version,
-        epoch: ctx.epoch(),
-        randomness_round: 0,
-        random_bytes: vector[],
-    };
-
-    let self = Random \{
-        id: object::randomness_state(),
-        inner: versioned::create(version, inner, ctx),
-    };
-    transfer::share_object(self);
-}
-
- - - -
- - - -## Function `load_inner_mut` - - - -

-fun load_inner_mut(self: &mut random::Random): &mut random::RandomInner
-
- - - -
-Implementation - - -

-fun load_inner_mut(
-    self: &mut Random,
-): &mut RandomInner \{
-    let version = versioned::version(&self.inner);
-
-    // Replace this with a lazy update function when we add a new version of the inner object.
-    assert!(version == CURRENT_VERSION, EWrongInnerVersion);
-    let inner: &mut RandomInner = versioned::load_value_mut(&mut self.inner);
-    assert!(inner.version == version, EWrongInnerVersion);
-    inner
-}
-
- - - -
- - - -## Function `load_inner` - - - -

-fun load_inner(self: &random::Random): &random::RandomInner
-
- - - -
-Implementation - - -

-fun load_inner(
-    self: &Random,
-): &RandomInner \{
-    let version = versioned::version(&self.inner);
-
-    // Replace this with a lazy update function when we add a new version of the inner object.
-    assert!(version == CURRENT_VERSION, EWrongInnerVersion);
-    let inner: &RandomInner = versioned::load_value(&self.inner);
-    assert!(inner.version == version, EWrongInnerVersion);
-    inner
-}
-
- - - -
- - - -## Function `update_randomness_state` - -Record new randomness. Called when executing the RandomnessStateUpdate system -transaction. - - -

-fun update_randomness_state(self: &mut random::Random, new_round: u64, new_bytes: vector<u8>, ctx: &tx_context::TxContext)
-
- - - -
-Implementation - - -

-fun update_randomness_state(
-    self: &mut Random,
-    new_round: u64,
-    new_bytes: vector<u8>,
-    ctx: &TxContext,
-) \{
-    // Validator will make a special system call with sender set as 0x0.
-    assert!(ctx.sender() == @0x0, ENotSystemAddress);
-
-    // Randomness should only be incremented.
-    let epoch = ctx.epoch();
-    let inner = self.load_inner_mut();
-    if (inner.randomness_round == 0 && inner.epoch == 0 && inner.random_bytes.is_empty()) \{
-        // First update should be for round zero.
-        assert!(new_round == 0, EInvalidRandomnessUpdate);
-    } else \{
-        // Subsequent updates should either increase epoch or increment randomness_round.
-        // Note that epoch may increase by more than 1 if an epoch is completed without
-        // randomness ever being generated in that epoch.
-        assert!(
-            (epoch > inner.epoch && new_round == 0) ||
-                (new_round == inner.randomness_round + 1),
-            EInvalidRandomnessUpdate
-        );
-    };
-
-    inner.epoch = ctx.epoch();
-    inner.randomness_round = new_round;
-    inner.random_bytes = new_bytes;
-}
-
- - - -
- - - -## Function `new_generator` - -Create a generator. Can be used to derive up to MAX_U16 * 32 random bytes. - - -

-public fun new_generator(r: &random::Random, ctx: &mut tx_context::TxContext): random::RandomGenerator
-
- - - -
-Implementation - - -

-public fun new_generator(r: &Random, ctx: &mut TxContext): RandomGenerator \{
-    let inner = load_inner(r);
-    let seed = hmac_sha3_256(
-        &inner.random_bytes,
-        &ctx.fresh_object_address().to_bytes()
-    );
-    RandomGenerator \{ seed, counter: 0, buffer: vector[] }
-}
-
- - - -
- - - -## Function `derive_next_block` - - - -

-fun derive_next_block(g: &mut random::RandomGenerator): vector<u8>
-
- - - -
-Implementation - - -

-fun derive_next_block(g: &mut RandomGenerator): vector<u8> \{
-    g.counter = g.counter + 1;
-    hmac_sha3_256(&g.seed, &bcs::to_bytes(&g.counter))
-}
-
- - - -
- - - -## Function `fill_buffer` - - - -

-fun fill_buffer(g: &mut random::RandomGenerator)
-
- - - -
-Implementation - - -

-fun fill_buffer(g: &mut RandomGenerator) \{
-    let next_block = derive_next_block(g);
-    vector::append(&mut g.buffer, next_block);
-}
-
- - - -
- - - -## Function `generate_bytes` - -Generate n random bytes. - - -

-public fun generate_bytes(g: &mut random::RandomGenerator, num_of_bytes: u16): vector<u8>
-
- - - -
-Implementation - - -

-public fun generate_bytes(g: &mut RandomGenerator, num_of_bytes: u16): vector<u8> \{
-    let mut result = vector[];
-    // Append RAND_OUTPUT_LEN size buffers directly without going through the generator's buffer.
-    let mut num_of_blocks = num_of_bytes / RAND_OUTPUT_LEN;
-    while (num_of_blocks > 0) \{
-        vector::append(&mut result, derive_next_block(g));
-        num_of_blocks = num_of_blocks - 1;
-    };
-    // Fill the generator's buffer if needed.
-    let num_of_bytes = num_of_bytes as u64;
-    if (vector::length(&g.buffer) < (num_of_bytes - vector::length(&result))) \{
-        fill_buffer(g);
-    };
-    // Take remaining bytes from the generator's buffer.
-    while (vector::length(&result) < num_of_bytes) \{
-        vector::push_back(&mut result, vector::pop_back(&mut g.buffer));
-    };
-    result
-}
-
- - - -
- - - -## Function `u256_from_bytes` - - - -

-fun u256_from_bytes(g: &mut random::RandomGenerator, num_of_bytes: u8): u256
-
- - - -
-Implementation - - -

-fun u256_from_bytes(g: &mut RandomGenerator, num_of_bytes: u8): u256 \{
-    if (vector::length(&g.buffer) < num_of_bytes as u64) \{
-        fill_buffer(g);
-    };
-    let mut result: u256 = 0;
-    let mut i = 0;
-    while (i < num_of_bytes) \{
-        let byte = vector::pop_back(&mut g.buffer);
-        result = (result << 8) + (byte as u256);
-        i = i + 1;
-    };
-    result
-}
-
- - - -
- - - -## Function `generate_u256` - -Generate a u256. - - -

-public fun generate_u256(g: &mut random::RandomGenerator): u256
-
- - - -
-Implementation - - -

-public fun generate_u256(g: &mut RandomGenerator): u256 \{
-    u256_from_bytes(g, 32)
-}
-
- - - -
- - - -## Function `generate_u128` - -Generate a u128. - - -

-public fun generate_u128(g: &mut random::RandomGenerator): u128
-
- - - -
-Implementation - - -

-public fun generate_u128(g: &mut RandomGenerator): u128 \{
-    u256_from_bytes(g, 16) as u128
-}
-
- - - -
- - - -## Function `generate_u64` - -Generate a u64. - - -

-public fun generate_u64(g: &mut random::RandomGenerator): u64
-
- - - -
-Implementation - - -

-public fun generate_u64(g: &mut RandomGenerator): u64 \{
-    u256_from_bytes(g, 8) as u64
-}
-
- - - -
- - - -## Function `generate_u32` - -Generate a u32. - - -

-public fun generate_u32(g: &mut random::RandomGenerator): u32
-
- - - -
-Implementation - - -

-public fun generate_u32(g: &mut RandomGenerator): u32 \{
-    u256_from_bytes(g, 4) as u32
-}
-
- - - -
- - - -## Function `generate_u16` - -Generate a u16. - - -

-public fun generate_u16(g: &mut random::RandomGenerator): u16
-
- - - -
-Implementation - - -

-public fun generate_u16(g: &mut RandomGenerator): u16 \{
-    u256_from_bytes(g, 2) as u16
-}
-
- - - -
- - - -## Function `generate_u8` - -Generate a u8. - - -

-public fun generate_u8(g: &mut random::RandomGenerator): u8
-
- - - -
-Implementation - - -

-public fun generate_u8(g: &mut RandomGenerator): u8 \{
-    u256_from_bytes(g, 1) as u8
-}
-
- - - -
- - - -## Function `generate_bool` - -Generate a boolean. - - -

-public fun generate_bool(g: &mut random::RandomGenerator): bool
-
- - - -
-Implementation - - -

-public fun generate_bool(g: &mut RandomGenerator): bool \{
-    (u256_from_bytes(g, 1) & 1) == 1
-}
-
- - - -
- - - -## Function `u128_in_range` - - - -

-fun u128_in_range(g: &mut random::RandomGenerator, min: u128, max: u128, num_of_bytes: u8): u128
-
- - - -
-Implementation - - -

-fun u128_in_range(g: &mut RandomGenerator, min: u128, max: u128, num_of_bytes: u8): u128 \{
-    assert!(min <= max, EInvalidRange);
-    if (min == max) \{
-        return min
-    };
-    // Pick a random number in [0, max - min] by generating a random number that is larger than max-min, and taking
-    // the modulo of the random number by the range size. Then add the min to the result to get a number in
-    // [min, max].
-    let range_size = (max - min) as u256 + 1;
-    let rand = u256_from_bytes(g, num_of_bytes);
-    min + (rand % range_size as u128)
-}
-
- - - -
- - - -## Function `generate_u128_in_range` - -Generate a random u128 in [min, max] (with a bias of 2^{-64}). - - -

-public fun generate_u128_in_range(g: &mut random::RandomGenerator, min: u128, max: u128): u128
-
- - - -
-Implementation - - -

-public fun generate_u128_in_range(g: &mut RandomGenerator, min: u128, max: u128): u128 \{
-    u128_in_range(g, min, max, 24)
-}
-
- - - -
- - - -## Function `generate_u64_in_range` - - - -

-public fun generate_u64_in_range(g: &mut random::RandomGenerator, min: u64, max: u64): u64
-
- - - -
-Implementation - - -

-public fun generate_u64_in_range(g: &mut RandomGenerator, min: u64, max: u64): u64 \{
-    u128_in_range(g, min as u128, max as u128, 16) as u64
-}
-
- - - -
- - - -## Function `generate_u32_in_range` - -Generate a random u32 in [min, max] (with a bias of 2^{-64}). - - -

-public fun generate_u32_in_range(g: &mut random::RandomGenerator, min: u32, max: u32): u32
-
- - - -
-Implementation - - -

-public fun generate_u32_in_range(g: &mut RandomGenerator, min: u32, max: u32): u32 \{
-    u128_in_range(g, min as u128, max as u128, 12) as u32
-}
-
- - - -
- - - -## Function `generate_u16_in_range` - -Generate a random u16 in [min, max] (with a bias of 2^{-64}). - - -

-public fun generate_u16_in_range(g: &mut random::RandomGenerator, min: u16, max: u16): u16
-
- - - -
-Implementation - - -

-public fun generate_u16_in_range(g: &mut RandomGenerator, min: u16, max: u16): u16 \{
-    u128_in_range(g, min as u128, max as u128, 10) as u16
-}
-
- - - -
- - - -## Function `generate_u8_in_range` - -Generate a random u8 in [min, max] (with a bias of 2^{-64}). - - -

-public fun generate_u8_in_range(g: &mut random::RandomGenerator, min: u8, max: u8): u8
-
- - - -
-Implementation - - -

-public fun generate_u8_in_range(g: &mut RandomGenerator, min: u8, max: u8): u8 \{
-    u128_in_range(g, min as u128, max as u128, 9) as u8
-}
-
- - - -
- - - -## Function `shuffle` - -Shuffle a vector using the random generator (Fisher–Yates/Knuth shuffle). - - -

-public fun shuffle<T>(g: &mut random::RandomGenerator, v: &mut vector<T>)
-
- - - -
-Implementation - - -

-public fun shuffle<T>(g: &mut RandomGenerator, v: &mut vector<T>) \{
-    let n = vector::length(v);
-    if (n == 0) \{
-        return
-    };
-    assert!(n <= U16_MAX, EInvalidLength);
-    let n = n as u16;
-    let mut i: u16 = 0;
-    let end = n - 1;
-    while (i < end) \{
-        let j = generate_u16_in_range(g, i, end);
-        vector::swap(v, i as u64, j as u64);
-        i = i + 1;
-    };
-}
-
- - - -
diff --git a/crates/iota-framework/docs/iota-framework/smr.mdx b/crates/iota-framework/docs/iota-framework/smr.mdx deleted file mode 100644 index 93b4b302918..00000000000 --- a/crates/iota-framework/docs/iota-framework/smr.mdx +++ /dev/null @@ -1,173 +0,0 @@ ---- -title: Module `0x2::smr` ---- -import Link from '@docusaurus/Link'; - - -`Coin` is the token used for migrated Shimmer users. -It has 6 decimals, and the smallest unit (10^-6) is called "glow". - - -- [Struct `SMR`](#0x2_smr_SMR) -- [Constants](#@Constants_0) -- [Function `init`](#0x2_smr_init) -- [Function `transfer`](#0x2_smr_transfer) - - -

-use 0x1::option;
-use 0x2::balance;
-use 0x2::coin;
-use 0x2::transfer;
-use 0x2::tx_context;
-use 0x2::url;
-
- - - - - -## Struct `SMR` - -Name of the coin - - -

-struct SMR has drop
-
- - - -
-Fields - - -
-
- -dummy_field: bool -
-
- -
-
- - -
- - - -## Constants - - - - -Sender is not @0x0 the system address. - - -

-const ENotSystemAddress: u64 = 1;
-
- - - - - - - -

-const EAlreadyMinted: u64 = 0;
-
- - - - - -The amount of Glows per Shimmer token based on the fact that micros is -10^-6 of a Shimmer token - - -

-const GLOW_PER_SMR: u64 = 1000000;
-
- - - - - -The total supply of Shimmer denominated in Glows - - -

-const TOTAL_SUPPLY_GLOWS: u64 = 1813620509061365;
-
- - - - - -## Function `init` - -Register the -SHIMMER coin. - - -

-fun init(witness: smr::SMR, ctx: &mut tx_context::TxContext)
-
- - - -
-Implementation - - -

-fun init(witness: SMR, ctx: &mut TxContext) \{
-    assert!(ctx.sender() == @0x0, ENotSystemAddress);
-    assert!(ctx.epoch() == 0, EAlreadyMinted);
-
-    let (treasury, metadata) = coin::create_currency(
-            witness,
-            6,
-            b"Shimmer",
-            b"SMR",
-            b"The original Shimmer (SMR) token as inherited from the Shimmer Network.",
-            option::some(url::new_unsafe_from_bytes(b"https://iota.org/smr-logo.png")),
-            ctx
-        );
-    transfer::public_freeze_object(metadata);
-    let supply = treasury.treasury_into_supply();
-    supply.destroy_supply();
-}
-
- - - -
- - - -## Function `transfer` - - - -

-public entry fun transfer(c: coin::Coin<smr::SMR>, recipient: address)
-
- - - -
-Implementation - - -

-public entry fun transfer(c: coin::Coin<SMR>, recipient: address) \{
-    transfer::public_transfer(c, recipient)
-}
-
- - - -
diff --git a/crates/iota-framework/docs/iota-framework/table.mdx b/crates/iota-framework/docs/iota-framework/table.mdx deleted file mode 100644 index 359e0041399..00000000000 --- a/crates/iota-framework/docs/iota-framework/table.mdx +++ /dev/null @@ -1,407 +0,0 @@ ---- -title: Module `0x2::table` ---- -import Link from '@docusaurus/Link'; - - -A table is a map-like collection. But unlike a traditional collection, it's keys and values are -not stored within the -Table value, but instead are stored using Iota's object system. The - -Table struct acts only as a handle into the object system to retrieve those keys and values. -Note that this means that -Table values with exactly the same key-value mapping will not be -equal, with -==, at runtime. For example -``` -let table1 = table::new(); -let table2 = table::new(); -table::add(&mut table1, 0, false); -table::add(&mut table1, 1, true); -table::add(&mut table2, 0, false); -table::add(&mut table2, 1, true); -// table1 does not equal table2, despite having the same entries -assert!(&table1 != &table2, 0); -``` - - -- [Resource `Table`](#0x2_table_Table) -- [Constants](#@Constants_0) -- [Function `new`](#0x2_table_new) -- [Function `add`](#0x2_table_add) -- [Function `borrow`](#0x2_table_borrow) -- [Function `borrow_mut`](#0x2_table_borrow_mut) -- [Function `remove`](#0x2_table_remove) -- [Function `contains`](#0x2_table_contains) -- [Function `length`](#0x2_table_length) -- [Function `is_empty`](#0x2_table_is_empty) -- [Function `destroy_empty`](#0x2_table_destroy_empty) -- [Function `drop`](#0x2_table_drop) - - -

-use 0x2::dynamic_field;
-use 0x2::object;
-use 0x2::tx_context;
-
- - - - - -## Resource `Table` - - - -

-struct Table<K: copy, drop, store, V: store> has store, key
-
- - - -
-Fields - - -
-
- -id: object::UID -
-
- the ID of this table -
-
- -size: u64 -
-
- the number of key-value pairs in the table -
-
- - -
- - - -## Constants - - - - - - -

-const ETableNotEmpty: u64 = 0;
-
- - - - - -## Function `new` - -Creates a new, empty table - - -

-public fun new<K: copy, drop, store, V: store>(ctx: &mut tx_context::TxContext): table::Table<K, V>
-
- - - -
-Implementation - - -

-public fun new<K: copy + drop + store, V: store>(ctx: &mut TxContext): Table<K, V> \{
-    Table \{
-        id: object::new(ctx),
-        size: 0,
-    }
-}
-
- - - -
- - - -## Function `add` - -Adds a key-value pair to the table -table: &mut Table<K, V> -Aborts with -iota::dynamic_field::EFieldAlreadyExists if the table already has an entry with -that key -k: K. - - -

-public fun add<K: copy, drop, store, V: store>(table: &mut table::Table<K, V>, k: K, v: V)
-
- - - -
-Implementation - - -

-public fun add<K: copy + drop + store, V: store>(table: &mut Table<K, V>, k: K, v: V) \{
-    field::add(&mut table.id, k, v);
-    table.size = table.size + 1;
-}
-
- - - -
- - - -## Function `borrow` - -Immutable borrows the value associated with the key in the table -table: &Table<K, V>. -Aborts with -iota::dynamic_field::EFieldDoesNotExist if the table does not have an entry with -that key -k: K. - - -

-public fun borrow<K: copy, drop, store, V: store>(table: &table::Table<K, V>, k: K): &V
-
- - - -
-Implementation - - -

-public fun borrow<K: copy + drop + store, V: store>(table: &Table<K, V>, k: K): &V \{
-    field::borrow(&table.id, k)
-}
-
- - - -
- - - -## Function `borrow_mut` - -Mutably borrows the value associated with the key in the table -table: &mut Table<K, V>. -Aborts with -iota::dynamic_field::EFieldDoesNotExist if the table does not have an entry with -that key -k: K. - - -

-public fun borrow_mut<K: copy, drop, store, V: store>(table: &mut table::Table<K, V>, k: K): &mut V
-
- - - -
-Implementation - - -

-public fun borrow_mut<K: copy + drop + store, V: store>(table: &mut Table<K, V>, k: K): &mut V \{
-    field::borrow_mut(&mut table.id, k)
-}
-
- - - -
- - - -## Function `remove` - -Removes the key-value pair in the table -table: &mut Table<K, V> and returns the value. -Aborts with -iota::dynamic_field::EFieldDoesNotExist if the table does not have an entry with -that key -k: K. - - -

-public fun remove<K: copy, drop, store, V: store>(table: &mut table::Table<K, V>, k: K): V
-
- - - -
-Implementation - - -

-public fun remove<K: copy + drop + store, V: store>(table: &mut Table<K, V>, k: K): V \{
-    let v = field::remove(&mut table.id, k);
-    table.size = table.size - 1;
-    v
-}
-
- - - -
- - - -## Function `contains` - -Returns true iff there is a value associated with the key -k: K in table -table: &Table<K, V> - - -

-public fun contains<K: copy, drop, store, V: store>(table: &table::Table<K, V>, k: K): bool
-
- - - -
-Implementation - - -

-public fun contains<K: copy + drop + store, V: store>(table: &Table<K, V>, k: K): bool \{
-    field::exists_with_type<K, V>(&table.id, k)
-}
-
- - - -
- - - -## Function `length` - -Returns the size of the table, the number of key-value pairs - - -

-public fun length<K: copy, drop, store, V: store>(table: &table::Table<K, V>): u64
-
- - - -
-Implementation - - -

-public fun length<K: copy + drop + store, V: store>(table: &Table<K, V>): u64 \{
-    table.size
-}
-
- - - -
- - - -## Function `is_empty` - -Returns true iff the table is empty (if -length returns -0) - - -

-public fun is_empty<K: copy, drop, store, V: store>(table: &table::Table<K, V>): bool
-
- - - -
-Implementation - - -

-public fun is_empty<K: copy + drop + store, V: store>(table: &Table<K, V>): bool \{
-    table.size == 0
-}
-
- - - -
- - - -## Function `destroy_empty` - -Destroys an empty table -Aborts with -ETableNotEmpty if the table still contains values - - -

-public fun destroy_empty<K: copy, drop, store, V: store>(table: table::Table<K, V>)
-
- - - -
-Implementation - - -

-public fun destroy_empty<K: copy + drop + store, V: store>(table: Table<K, V>) \{
-    let Table \{ id, size } = table;
-    assert!(size == 0, ETableNotEmpty);
-    id.delete()
-}
-
- - - -
- - - -## Function `drop` - -Drop a possibly non-empty table. -Usable only if the value type -V has the -drop ability - - -

-public fun drop<K: copy, drop, store, V: drop, store>(table: table::Table<K, V>)
-
- - - -
-Implementation - - -

-public fun drop<K: copy + drop + store, V: drop + store>(table: Table<K, V>) \{
-    let Table \{ id, size: _ } = table;
-    id.delete()
-}
-
- - - -
diff --git a/crates/iota-framework/docs/iota-framework/table_vec.mdx b/crates/iota-framework/docs/iota-framework/table_vec.mdx deleted file mode 100644 index 306cfc95a22..00000000000 --- a/crates/iota-framework/docs/iota-framework/table_vec.mdx +++ /dev/null @@ -1,463 +0,0 @@ ---- -title: Module `0x2::table_vec` ---- -import Link from '@docusaurus/Link'; - - -A basic scalable vector library implemented using -Table. - - -- [Struct `TableVec`](#0x2_table_vec_TableVec) -- [Constants](#@Constants_0) -- [Function `empty`](#0x2_table_vec_empty) -- [Function `singleton`](#0x2_table_vec_singleton) -- [Function `length`](#0x2_table_vec_length) -- [Function `is_empty`](#0x2_table_vec_is_empty) -- [Function `borrow`](#0x2_table_vec_borrow) -- [Function `push_back`](#0x2_table_vec_push_back) -- [Function `borrow_mut`](#0x2_table_vec_borrow_mut) -- [Function `pop_back`](#0x2_table_vec_pop_back) -- [Function `destroy_empty`](#0x2_table_vec_destroy_empty) -- [Function `drop`](#0x2_table_vec_drop) -- [Function `swap`](#0x2_table_vec_swap) -- [Function `swap_remove`](#0x2_table_vec_swap_remove) - - -

-use 0x2::table;
-use 0x2::tx_context;
-
- - - - - -## Struct `TableVec` - - - -

-struct TableVec<Element: store> has store
-
- - - -
-Fields - - -
-
- -contents: table::Table<u64, Element> -
-
- The contents of the table vector. -
-
- - -
- - - -## Constants - - - - - - -

-const EIndexOutOfBound: u64 = 0;
-
- - - - - - - -

-const ETableNonEmpty: u64 = 1;
-
- - - - - -## Function `empty` - -Create an empty TableVec. - - -

-public fun empty<Element: store>(ctx: &mut tx_context::TxContext): table_vec::TableVec<Element>
-
- - - -
-Implementation - - -

-public fun empty<Element: store>(ctx: &mut TxContext): TableVec<Element> \{
-    TableVec \{
-        contents: table::new(ctx)
-    }
-}
-
- - - -
- - - -## Function `singleton` - -Return a TableVec of size one containing element -e. - - -

-public fun singleton<Element: store>(e: Element, ctx: &mut tx_context::TxContext): table_vec::TableVec<Element>
-
- - - -
-Implementation - - -

-public fun singleton<Element: store>(e: Element, ctx: &mut TxContext): TableVec<Element> \{
-    let mut t = empty(ctx);
-    t.push_back(e);
-    t
-}
-
- - - -
- - - -## Function `length` - -Return the length of the TableVec. - - -

-public fun length<Element: store>(t: &table_vec::TableVec<Element>): u64
-
- - - -
-Implementation - - -

-public fun length<Element: store>(t: &TableVec<Element>): u64 \{
-    t.contents.length()
-}
-
- - - -
- - - -## Function `is_empty` - -Return if the TableVec is empty or not. - - -

-public fun is_empty<Element: store>(t: &table_vec::TableVec<Element>): bool
-
- - - -
-Implementation - - -

-public fun is_empty<Element: store>(t: &TableVec<Element>): bool \{
-    t.length() == 0
-}
-
- - - -
- - - -## Function `borrow` - -Acquire an immutable reference to the -ith element of the TableVec -t. -Aborts if -i is out of bounds. - - -

-public fun borrow<Element: store>(t: &table_vec::TableVec<Element>, i: u64): &Element
-
- - - -
-Implementation - - -

-public fun borrow<Element: store>(t: &TableVec<Element>, i: u64): &Element \{
-    assert!(t.length() > i, EIndexOutOfBound);
-    &t.contents[i]
-}
-
- - - -
- - - -## Function `push_back` - -Add element -e to the end of the TableVec -t. - - -

-public fun push_back<Element: store>(t: &mut table_vec::TableVec<Element>, e: Element)
-
- - - -
-Implementation - - -

-public fun push_back<Element: store>(t: &mut TableVec<Element>, e: Element) \{
-    let key = t.length();
-    t.contents.add(key, e);
-}
-
- - - -
- - - -## Function `borrow_mut` - -Return a mutable reference to the -ith element in the TableVec -t. -Aborts if -i is out of bounds. - - -

-public fun borrow_mut<Element: store>(t: &mut table_vec::TableVec<Element>, i: u64): &mut Element
-
- - - -
-Implementation - - -

-public fun borrow_mut<Element: store>(t: &mut TableVec<Element>, i: u64): &mut Element \{
-    assert!(t.length() > i, EIndexOutOfBound);
-    &mut t.contents[i]
-}
-
- - - -
- - - -## Function `pop_back` - -Pop an element from the end of TableVec -t. -Aborts if -t is empty. - - -

-public fun pop_back<Element: store>(t: &mut table_vec::TableVec<Element>): Element
-
- - - -
-Implementation - - -

-public fun pop_back<Element: store>(t: &mut TableVec<Element>): Element \{
-    let length = length(t);
-    assert!(length > 0, EIndexOutOfBound);
-    t.contents.remove(length - 1)
-}
-
- - - -
- - - -## Function `destroy_empty` - -Destroy the TableVec -t. -Aborts if -t is not empty. - - -

-public fun destroy_empty<Element: store>(t: table_vec::TableVec<Element>)
-
- - - -
-Implementation - - -

-public fun destroy_empty<Element: store>(t: TableVec<Element>) \{
-    assert!(length(&t) == 0, ETableNonEmpty);
-    let TableVec \{ contents } = t;
-    contents.destroy_empty();
-}
-
- - - -
- - - -## Function `drop` - -Drop a possibly non-empty TableVec -t. -Usable only if the value type -Element has the -drop ability - - -

-public fun drop<Element: drop, store>(t: table_vec::TableVec<Element>)
-
- - - -
-Implementation - - -

-public fun drop<Element: drop + store>(t: TableVec<Element>) \{
-    let TableVec \{ contents } = t;
-    contents.drop()
-}
-
- - - -
- - - -## Function `swap` - -Swaps the elements at the -ith and -jth indices in the TableVec -t. -Aborts if -i or -j is out of bounds. - - -

-public fun swap<Element: store>(t: &mut table_vec::TableVec<Element>, i: u64, j: u64)
-
- - - -
-Implementation - - -

-public fun swap<Element: store>(t: &mut TableVec<Element>, i: u64, j: u64) \{
-    assert!(t.length() > i, EIndexOutOfBound);
-    assert!(t.length() > j, EIndexOutOfBound);
-    if (i == j) \{ return };
-    let element_i = t.contents.remove(i);
-    let element_j = t.contents.remove(j);
-    t.contents.add(j, element_i);
-    t.contents.add(i, element_j);
-}
-
- - - -
- - - -## Function `swap_remove` - -Swap the -ith element of the TableVec -t with the last element and then pop the TableVec. -This is O(1), but does not preserve ordering of elements in the TableVec. -Aborts if -i is out of bounds. - - -

-public fun swap_remove<Element: store>(t: &mut table_vec::TableVec<Element>, i: u64): Element
-
- - - -
-Implementation - - -

-public fun swap_remove<Element: store>(t: &mut TableVec<Element>, i: u64): Element \{
-    assert!(t.length() > i, EIndexOutOfBound);
-    let last_idx = t.length() - 1;
-    t.swap(i, last_idx);
-    t.pop_back()
-}
-
- - - -
diff --git a/crates/iota-framework/docs/iota-framework/timelock.mdx b/crates/iota-framework/docs/iota-framework/timelock.mdx deleted file mode 100644 index d711611e79a..00000000000 --- a/crates/iota-framework/docs/iota-framework/timelock.mdx +++ /dev/null @@ -1,997 +0,0 @@ ---- -title: Module `0x2::timelock` ---- -import Link from '@docusaurus/Link'; - - -A timelock implementation. - - -- [Resource `TimeLock`](#0x2_timelock_TimeLock) -- [Struct `SystemTimelockCap`](#0x2_timelock_SystemTimelockCap) -- [Constants](#@Constants_0) -- [Function `lock`](#0x2_timelock_lock) -- [Function `lock_with_label`](#0x2_timelock_lock_with_label) -- [Function `lock_and_transfer`](#0x2_timelock_lock_and_transfer) -- [Function `lock_with_label_and_transfer`](#0x2_timelock_lock_with_label_and_transfer) -- [Function `unlock`](#0x2_timelock_unlock) -- [Function `join`](#0x2_timelock_join) -- [Function `join_vec`](#0x2_timelock_join_vec) -- [Function `split`](#0x2_timelock_split) -- [Function `split_balance`](#0x2_timelock_split_balance) -- [Function `transfer_to_sender`](#0x2_timelock_transfer_to_sender) -- [Function `system_pack`](#0x2_timelock_system_pack) -- [Function `system_unpack`](#0x2_timelock_system_unpack) -- [Function `type_name`](#0x2_timelock_type_name) -- [Function `expiration_timestamp_ms`](#0x2_timelock_expiration_timestamp_ms) -- [Function `is_locked`](#0x2_timelock_is_locked) -- [Function `remaining_time`](#0x2_timelock_remaining_time) -- [Function `locked`](#0x2_timelock_locked) -- [Function `label`](#0x2_timelock_label) -- [Function `is_labeled_with`](#0x2_timelock_is_labeled_with) -- [Function `pack`](#0x2_timelock_pack) -- [Function `unpack`](#0x2_timelock_unpack) -- [Function `transfer`](#0x2_timelock_transfer) -- [Function `check_expiration_timestamp_ms`](#0x2_timelock_check_expiration_timestamp_ms) -- [Function `new_system_timelock_cap`](#0x2_timelock_new_system_timelock_cap) - - -

-use 0x1::ascii;
-use 0x1::option;
-use 0x1::string;
-use 0x1::type_name;
-use 0x2::balance;
-use 0x2::labeler;
-use 0x2::object;
-use 0x2::transfer;
-use 0x2::tx_context;
-
- - - - - -## Resource `TimeLock` - - -TimeLock struct that holds a locked object. - - -

-struct TimeLock<T: store> has key
-
- - - -
-Fields - - -
-
- -id: object::UID -
-
- -
-
- -locked: T -
-
- The locked object. -
-
- -expiration_timestamp_ms: u64 -
-
- This is the epoch time stamp of when the lock expires. -
-
- -label: option::Option<string::String> -
-
- Timelock related label. -
-
- - -
- - - -## Struct `SystemTimelockCap` - - -SystemTimelockCap allows to -pack and -unpack TimeLocks - - -

-struct SystemTimelockCap has store
-
- - - -
-Fields - - -
-
- -dummy_field: bool -
-
- -
-
- - -
- - - -## Constants - - - - -Sender is not @0x0 the system address. - - -

-const ENotSystemAddress: u64 = 1;
-
- - - - - -For when trying to join two time-locked balances with different expiration time. - - -

-const EDifferentExpirationTime: u64 = 4;
-
- - - - - -For when trying to join two time-locked balances with different labels. - - -

-const EDifferentLabels: u64 = 5;
-
- - - - - -Expiration timestamp of the lock is in the past. - - -

-const EExpireEpochIsPast: u64 = 2;
-
- - - - - -The -new function was called at a non-genesis epoch. - - -

-const ENotCalledAtGenesis: u64 = 0;
-
- - - - - -The lock has not expired yet. - - -

-const ENotExpiredYet: u64 = 3;
-
- - - - - -## Function `lock` - -Function to lock an object till a unix timestamp in milliseconds. - - -

-public fun lock<T: store>(locked: T, expiration_timestamp_ms: u64, ctx: &mut tx_context::TxContext): timelock::TimeLock<T>
-
- - - -
-Implementation - - -

-public fun lock<T: store>(locked: T, expiration_timestamp_ms: u64, ctx: &mut TxContext): TimeLock<T> \{
-    // Check that `expiration_timestamp_ms` is valid.
-    check_expiration_timestamp_ms(expiration_timestamp_ms, ctx);
-
-    // Create a timelock.
-    pack(locked, expiration_timestamp_ms, option::none(), ctx)
-}
-
- - - -
- - - -## Function `lock_with_label` - -Function to lock a labeled object till a unix timestamp in milliseconds. - - -

-public fun lock_with_label<T: store, L>(_: &labeler::LabelerCap<L>, locked: T, expiration_timestamp_ms: u64, ctx: &mut tx_context::TxContext): timelock::TimeLock<T>
-
- - - -
-Implementation - - -

-public fun lock_with_label<T: store, L>(
-    _: &LabelerCap<L>,
-    locked: T,
-    expiration_timestamp_ms: u64,
-    ctx: &mut TxContext
-): TimeLock<T> \{
-    // Check that `expiration_timestamp_ms` is valid.
-    check_expiration_timestamp_ms(expiration_timestamp_ms, ctx);
-
-    // Calculate a label value.
-    let label = type_name<L>();
-
-    // Create a labeled timelock.
-    pack(locked, expiration_timestamp_ms, option::some(label), ctx)
-}
-
- - - -
- - - -## Function `lock_and_transfer` - -Function to lock an object -obj until -expiration_timestamp_ms and transfer it to address -to. -Since -Timelock<T> does not support public transfer, use this function to lock an object to an address. - - -

-public fun lock_and_transfer<T: store>(obj: T, to: address, expiration_timestamp_ms: u64, ctx: &mut tx_context::TxContext)
-
- - - -
-Implementation - - -

-public fun lock_and_transfer<T: store>(
-    obj: T,
-    to: address,
-    expiration_timestamp_ms: u64,
-    ctx: &mut TxContext
-) \{
-    transfer(lock(obj, expiration_timestamp_ms, ctx), to);
-}
-
- - - -
- - - -## Function `lock_with_label_and_transfer` - -Function to lock a labeled object -obj until -expiration_timestamp_ms and transfer it to address -to. -Since -Timelock<T> does not support public transfer, use this function to lock a labeled object to an address. - - -

-public fun lock_with_label_and_transfer<T: store, L>(labeler: &labeler::LabelerCap<L>, obj: T, to: address, expiration_timestamp_ms: u64, ctx: &mut tx_context::TxContext)
-
- - - -
-Implementation - - -

-public fun lock_with_label_and_transfer<T: store, L>(
-    labeler: &LabelerCap<L>,
-    obj: T,
-    to: address,
-    expiration_timestamp_ms: u64,
-    ctx: &mut TxContext
-) \{
-    transfer(lock_with_label(labeler, obj, expiration_timestamp_ms, ctx), to);
-}
-
- - - -
- - - -## Function `unlock` - -Function to unlock the object from a -TimeLock. - - -

-public fun unlock<T: store>(self: timelock::TimeLock<T>, ctx: &tx_context::TxContext): T
-
- - - -
-Implementation - - -

-public fun unlock<T: store>(self: TimeLock<T>, ctx: &TxContext): T \{
-    // Unpack the timelock.
-    let (locked, expiration_timestamp_ms, _) = unpack(self);
-
-    // Check if the lock has expired.
-    assert!(expiration_timestamp_ms <= ctx.epoch_timestamp_ms(), ENotExpiredYet);
-
-    locked
-}
-
- - - -
- - - -## Function `join` - -Join two -TimeLock<Balance<T>> together. - - -

-public fun join<T>(self: &mut timelock::TimeLock<balance::Balance<T>>, other: timelock::TimeLock<balance::Balance<T>>)
-
- - - -
-Implementation - - -

-public fun join<T>(self: &mut TimeLock<Balance<T>>, other: TimeLock<Balance<T>>) \{
-    // Check the preconditions.
-    assert!(self.expiration_timestamp_ms() == other.expiration_timestamp_ms(), EDifferentExpirationTime);
-    assert!(self.label() == other.label(), EDifferentLabels);
-
-    // Unpack the time-locked balance.
-    let (value, _, _) = unpack(other);
-
-    // Join the balances.
-    self.locked.join(value);
-}
-
- - - -
- - - -## Function `join_vec` - -Join everything in -others with -self. - - -

-public fun join_vec<T>(self: &mut timelock::TimeLock<balance::Balance<T>>, others: vector<timelock::TimeLock<balance::Balance<T>>>)
-
- - - -
-Implementation - - -

-public fun join_vec<T>(self: &mut TimeLock<Balance<T>>, mut others: vector<TimeLock<Balance<T>>>) \{
-    // Create useful variables.
-    let (mut i, len) = (0, others.length());
-
-    // Join all the balances.
-    while (i < len) \{
-        let other = others.pop_back();
-        Self::join(self, other);
-        i = i + 1
-    };
-
-    // Destroy the empty vector.
-    vector::destroy_empty(others)
-}
-
- - - -
- - - -## Function `split` - -Split a -TimeLock<Balance<T>> and take a sub balance from it. - - -

-public fun split<T>(self: &mut timelock::TimeLock<balance::Balance<T>>, value: u64, ctx: &mut tx_context::TxContext): timelock::TimeLock<balance::Balance<T>>
-
- - - -
-Implementation - - -

-public fun split<T>(self: &mut TimeLock<Balance<T>>, value: u64, ctx: &mut TxContext): TimeLock<Balance<T>> \{
-    // Split the locked balance.
-    let value = self.locked.split(value);
-
-    // Pack the split balance into a timelock.
-    pack(value, self.expiration_timestamp_ms(), self.label(), ctx)
-}
-
- - - -
- - - -## Function `split_balance` - -Split the given -TimeLock<Balance<T>> into two parts, one with principal -value, -and transfer the newly split part to the sender address. - - -

-public entry fun split_balance<T>(self: &mut timelock::TimeLock<balance::Balance<T>>, value: u64, ctx: &mut tx_context::TxContext)
-
- - - -
-Implementation - - -

-public entry fun split_balance<T>(self: &mut TimeLock<Balance<T>>, value: u64, ctx: &mut TxContext) \{
-    split(self, value, ctx).transfer_to_sender(ctx)
-}
-
- - - -
- - - -## Function `transfer_to_sender` - -A utility function to transfer a -TimeLock to the sender. - - -

-public fun transfer_to_sender<T: store>(lock: timelock::TimeLock<T>, ctx: &tx_context::TxContext)
-
- - - -
-Implementation - - -

-public fun transfer_to_sender<T: store>(lock: TimeLock<T>, ctx: &TxContext) \{
-    transfer(lock, ctx.sender())
-}
-
- - - -
- - - -## Function `system_pack` - -A utility function to pack a -TimeLock that can be invoked only by a system package. - - -

-public fun system_pack<T: store>(_: &timelock::SystemTimelockCap, locked: T, expiration_timestamp_ms: u64, label: option::Option<string::String>, ctx: &mut tx_context::TxContext): timelock::TimeLock<T>
-
- - - -
-Implementation - - -

-public fun system_pack<T: store>(
-    _: &SystemTimelockCap,
-    locked: T,
-    expiration_timestamp_ms: u64,
-    label: Option<String>,
-    ctx: &mut TxContext): TimeLock<T>
-\{
-    pack(locked, expiration_timestamp_ms, label, ctx)
-}
-
- - - -
- - - -## Function `system_unpack` - -An utility function to unpack a -TimeLock that can be invoked only by a system package. - - -

-public fun system_unpack<T: store>(_: &timelock::SystemTimelockCap, lock: timelock::TimeLock<T>): (T, u64, option::Option<string::String>)
-
- - - -
-Implementation - - -

-public fun system_unpack<T: store>(_: &SystemTimelockCap, lock: TimeLock<T>): (T, u64, Option<String>) \{
-    unpack(lock)
-}
-
- - - -
- - - -## Function `type_name` - -Return a fully qualified type name with the original package IDs -that is used as type related a label value. - - -

-public fun type_name<L>(): string::String
-
- - - -
-Implementation - - -

-public fun type_name<L>(): String \{
-    string::from_ascii(std::type_name::get_with_original_ids<L>().into_string())
-}
-
- - - -
- - - -## Function `expiration_timestamp_ms` - -Function to get the expiration timestamp of a -TimeLock. - - -

-public fun expiration_timestamp_ms<T: store>(self: &timelock::TimeLock<T>): u64
-
- - - -
-Implementation - - -

-public fun expiration_timestamp_ms<T: store>(self: &TimeLock<T>): u64 \{
-    self.expiration_timestamp_ms
-}
-
- - - -
- - - -## Function `is_locked` - -Function to check if a -TimeLock is locked. - - -

-public fun is_locked<T: store>(self: &timelock::TimeLock<T>, ctx: &tx_context::TxContext): bool
-
- - - -
-Implementation - - -

-public fun is_locked<T: store>(self: &TimeLock<T>, ctx: &TxContext): bool \{
-    self.remaining_time(ctx) > 0
-}
-
- - - -
- - - -## Function `remaining_time` - -Function to get the remaining time of a -TimeLock. -Returns 0 if the lock has expired. - - -

-public fun remaining_time<T: store>(self: &timelock::TimeLock<T>, ctx: &tx_context::TxContext): u64
-
- - - -
-Implementation - - -

-public fun remaining_time<T: store>(self: &TimeLock<T>, ctx: &TxContext): u64 \{
-    // Get the epoch timestamp.
-    let current_timestamp_ms = ctx.epoch_timestamp_ms();
-
-    // Check if the lock has expired.
-    if (self.expiration_timestamp_ms < current_timestamp_ms) \{
-        return 0
-    };
-
-    // Calculate the remaining time.
-    self.expiration_timestamp_ms - current_timestamp_ms
-}
-
- - - -
- - - -## Function `locked` - -Function to get the locked object of a -TimeLock. - - -

-public fun locked<T: store>(self: &timelock::TimeLock<T>): &T
-
- - - -
-Implementation - - -

-public fun locked<T: store>(self: &TimeLock<T>): &T \{
-    &self.locked
-}
-
- - - -
- - - -## Function `label` - -Function to get the label of a -TimeLock. - - -

-public fun label<T: store>(self: &timelock::TimeLock<T>): option::Option<string::String>
-
- - - -
-Implementation - - -

-public fun label<T: store>(self: &TimeLock<T>): Option<String> \{
-    self.label
-}
-
- - - -
- - - -## Function `is_labeled_with` - -Check if a -TimeLock is labeled with the type -L. - - -

-public fun is_labeled_with<T: store, L>(self: &timelock::TimeLock<T>): bool
-
- - - -
-Implementation - - -

-public fun is_labeled_with<T: store, L>(self: &TimeLock<T>): bool \{
-    if (self.label.is_some()) \{
-        self.label.borrow() == type_name<L>()
-    }
-    else \{
-        false
-    }
-}
-
- - - -
- - - -## Function `pack` - -A utility function to pack a -TimeLock. - - -

-fun pack<T: store>(locked: T, expiration_timestamp_ms: u64, label: option::Option<string::String>, ctx: &mut tx_context::TxContext): timelock::TimeLock<T>
-
- - - -
-Implementation - - -

-fun pack<T: store>(
-    locked: T,
-    expiration_timestamp_ms: u64,
-    label: Option<String>,
-    ctx: &mut TxContext): TimeLock<T>
-\{
-    // Create a timelock.
-    TimeLock \{
-        id: object::new(ctx),
-        locked,
-        expiration_timestamp_ms,
-        label,
-    }
-}
-
- - - -
- - - -## Function `unpack` - -An utility function to unpack a -TimeLock. - - -

-fun unpack<T: store>(lock: timelock::TimeLock<T>): (T, u64, option::Option<string::String>)
-
- - - -
-Implementation - - -

-fun unpack<T: store>(lock: TimeLock<T>): (T, u64, Option<String>) \{
-    // Unpack the timelock.
-    let TimeLock \{
-        id,
-        locked,
-        expiration_timestamp_ms,
-        label,
-    } = lock;
-
-    // Delete the timelock.
-    object::delete(id);
-
-    (locked, expiration_timestamp_ms, label)
-}
-
- - - -
- - - -## Function `transfer` - -A utility function to transfer a -TimeLock to a receiver. - - -

-fun transfer<T: store>(lock: timelock::TimeLock<T>, receiver: address)
-
- - - -
-Implementation - - -

-fun transfer<T: store>(lock: TimeLock<T>, receiver: address) \{
-    transfer::transfer(lock, receiver);
-}
-
- - - -
- - - -## Function `check_expiration_timestamp_ms` - -An utility function to check that the -expiration_timestamp_ms value is valid. - - -

-fun check_expiration_timestamp_ms(expiration_timestamp_ms: u64, ctx: &tx_context::TxContext)
-
- - - -
-Implementation - - -

-fun check_expiration_timestamp_ms(expiration_timestamp_ms: u64, ctx: &TxContext) \{
-    // Get the epoch timestamp.
-    let epoch_timestamp_ms = ctx.epoch_timestamp_ms();
-
-    // Check that `expiration_timestamp_ms` is valid.
-    assert!(expiration_timestamp_ms > epoch_timestamp_ms, EExpireEpochIsPast);
-}
-
- - - -
- - - -## Function `new_system_timelock_cap` - -Create a -SystemTimelockCap. -This should be called only once during genesis creation. - - -

-fun new_system_timelock_cap(ctx: &tx_context::TxContext): timelock::SystemTimelockCap
-
- - - -
-Implementation - - -

-fun new_system_timelock_cap(ctx: &TxContext): SystemTimelockCap \{
-    assert!(ctx.sender() == @0x0, ENotSystemAddress);
-    assert!(ctx.epoch() == 0, ENotCalledAtGenesis);
-
-    SystemTimelockCap \{}
-}
-
- - - -
diff --git a/crates/iota-framework/docs/iota-framework/token.mdx b/crates/iota-framework/docs/iota-framework/token.mdx deleted file mode 100644 index cd923fd4c34..00000000000 --- a/crates/iota-framework/docs/iota-framework/token.mdx +++ /dev/null @@ -1,2257 +0,0 @@ ---- -title: Module `0x2::token` ---- -import Link from '@docusaurus/Link'; - - -The Token module which implements a Closed Loop Token with a configurable -policy. The policy is defined by a set of rules that must be satisfied for -an action to be performed on the token. - -The module is designed to be used with a -TreasuryCap to allow for minting -and burning of the -Tokens. And can act as a replacement / extension or a -companion to existing open-loop ( -Coin) systems. - -``` -Module: iota::balance iota::coin iota::token -Main type: `Balance` `Coin` `Token` -Capability: `Supply` <----> `TreasuryCap` <----> `TreasuryCap` -Abilities: store key + store key -``` - -The Token system allows for fine-grained control over the actions performed -on the token. And hence it is highly suitable for applications that require -control over the currency which a simple open-loop system can't provide. - - -- [Resource `Token`](#0x2_token_Token) -- [Resource `TokenPolicyCap`](#0x2_token_TokenPolicyCap) -- [Resource `TokenPolicy`](#0x2_token_TokenPolicy) -- [Struct `ActionRequest`](#0x2_token_ActionRequest) -- [Struct `RuleKey`](#0x2_token_RuleKey) -- [Struct `TokenPolicyCreated`](#0x2_token_TokenPolicyCreated) -- [Constants](#@Constants_0) -- [Function `new_policy`](#0x2_token_new_policy) -- [Function `share_policy`](#0x2_token_share_policy) -- [Function `transfer`](#0x2_token_transfer) -- [Function `spend`](#0x2_token_spend) -- [Function `to_coin`](#0x2_token_to_coin) -- [Function `from_coin`](#0x2_token_from_coin) -- [Function `join`](#0x2_token_join) -- [Function `split`](#0x2_token_split) -- [Function `zero`](#0x2_token_zero) -- [Function `destroy_zero`](#0x2_token_destroy_zero) -- [Function `keep`](#0x2_token_keep) -- [Function `new_request`](#0x2_token_new_request) -- [Function `confirm_request`](#0x2_token_confirm_request) -- [Function `confirm_request_mut`](#0x2_token_confirm_request_mut) -- [Function `confirm_with_policy_cap`](#0x2_token_confirm_with_policy_cap) -- [Function `confirm_with_treasury_cap`](#0x2_token_confirm_with_treasury_cap) -- [Function `add_approval`](#0x2_token_add_approval) -- [Function `add_rule_config`](#0x2_token_add_rule_config) -- [Function `rule_config`](#0x2_token_rule_config) -- [Function `rule_config_mut`](#0x2_token_rule_config_mut) -- [Function `remove_rule_config`](#0x2_token_remove_rule_config) -- [Function `has_rule_config`](#0x2_token_has_rule_config) -- [Function `has_rule_config_with_type`](#0x2_token_has_rule_config_with_type) -- [Function `allow`](#0x2_token_allow) -- [Function `disallow`](#0x2_token_disallow) -- [Function `add_rule_for_action`](#0x2_token_add_rule_for_action) -- [Function `remove_rule_for_action`](#0x2_token_remove_rule_for_action) -- [Function `mint`](#0x2_token_mint) -- [Function `burn`](#0x2_token_burn) -- [Function `flush`](#0x2_token_flush) -- [Function `is_allowed`](#0x2_token_is_allowed) -- [Function `rules`](#0x2_token_rules) -- [Function `spent_balance`](#0x2_token_spent_balance) -- [Function `value`](#0x2_token_value) -- [Function `transfer_action`](#0x2_token_transfer_action) -- [Function `spend_action`](#0x2_token_spend_action) -- [Function `to_coin_action`](#0x2_token_to_coin_action) -- [Function `from_coin_action`](#0x2_token_from_coin_action) -- [Function `action`](#0x2_token_action) -- [Function `amount`](#0x2_token_amount) -- [Function `sender`](#0x2_token_sender) -- [Function `recipient`](#0x2_token_recipient) -- [Function `approvals`](#0x2_token_approvals) -- [Function `spent`](#0x2_token_spent) -- [Function `key`](#0x2_token_key) - - -

-use 0x1::option;
-use 0x1::string;
-use 0x1::type_name;
-use 0x2::balance;
-use 0x2::coin;
-use 0x2::dynamic_field;
-use 0x2::event;
-use 0x2::object;
-use 0x2::transfer;
-use 0x2::tx_context;
-use 0x2::vec_map;
-use 0x2::vec_set;
-
- - - - - -## Resource `Token` - -A single -Token with -Balance inside. Can only be owned by an address, -and actions performed on it must be confirmed in a matching -TokenPolicy. - - -

-struct Token<T> has key
-
- - - -
-Fields - - -
-
- -id: object::UID -
-
- -
-
- -balance: balance::Balance<T> -
-
- The Balance of the -Token. -
-
- - -
- - - -## Resource `TokenPolicyCap` - -A Capability that manages a single -TokenPolicy specified in the -for -field. Created together with -TokenPolicy in the -new function. - - -

-struct TokenPolicyCap<T> has store, key
-
- - - -
-Fields - - -
-
- -id: object::UID -
-
- -
-
- -for: object::ID -
-
- -
-
- - -
- - - -## Resource `TokenPolicy` - - -TokenPolicy represents a set of rules that define what actions can be -performed on a -Token and which -Rules must be satisfied for the -action to succeed. - -- For the sake of availability, -TokenPolicy is a -key-only object. -- Each -TokenPolicy is managed by a matching -TokenPolicyCap. -- For an action to become available, there needs to be a record in the - -rules VecMap. To allow an action to be performed freely, there's an - -allow function that can be called by the -TokenPolicyCap owner. - - -

-struct TokenPolicy<T> has key
-
- - - -
-Fields - - -
-
- -id: object::UID -
-
- -
-
- -spent_balance: balance::Balance<T> -
-
- The balance that is effectively spent by the user on the "spend" - action. However, actual decrease of the supply can only be done by - the -TreasuryCap owner when -flush is called. - - This balance is effectively spent and cannot be accessed by anyone - but the -TreasuryCap owner. -
-
- -rules: vec_map::VecMap<string::String, vec_set::VecSet<type_name::TypeName>> -
-
- The set of rules that define what actions can be performed on the - token. For each "action" there's a set of Rules that must be - satisfied for the -ActionRequest to be confirmed. -
-
- - -
- - - -## Struct `ActionRequest` - -A request to perform an "Action" on a token. Stores the information -about the action to be performed and must be consumed by the -confirm_request -or -confirm_request_mut functions when the Rules are satisfied. - - -

-struct ActionRequest<T>
-
- - - -
-Fields - - -
-
- -name: string::String -
-
- Name of the Action to look up in the Policy. Name can be one of the - default actions: -transfer, -spend, -to_coin, -from_coin or a - custom action. -
-
- -amount: u64 -
-
- Amount is present in all of the txs -
-
- -sender: address -
-
- Sender is a permanent field always -
-
- -recipient: option::Option<address> -
-
- Recipient is only available in -transfer action. -
-
- -spent_balance: option::Option<balance::Balance<T>> -
-
- The balance to be "spent" in the -TokenPolicy, only available - in the -spend action. -
-
- -approvals: vec_set::VecSet<type_name::TypeName> -
-
- Collected approvals (stamps) from completed -Rules. They're matched - against -TokenPolicy.rules to determine if the request can be - confirmed. -
-
- - -
- - - -## Struct `RuleKey` - -Dynamic field key for the -TokenPolicy to store the -Config for a -specific action -Rule. There can be only one configuration per - -Rule per -TokenPolicy. - - -

-struct RuleKey<T> has copy, drop, store
-
- - - -
-Fields - - -
-
- -is_protected: bool -
-
- -
-
- - -
- - - -## Struct `TokenPolicyCreated` - -An event emitted when a -TokenPolicy is created and shared. Because - -TokenPolicy can only be shared (and potentially frozen in the future), -we emit this event in the -share_policy function and mark it as mutable. - - -

-struct TokenPolicyCreated<T> has copy, drop
-
- - - -
-Fields - - -
-
- -id: object::ID -
-
- ID of the -TokenPolicy that was created. -
-
- -is_mutable: bool -
-
- Whether the -TokenPolicy is "shared" (mutable) or "frozen" - (immutable) - TBD. -
-
- - -
- - - -## Constants - - - - -Trying to perform an admin action with a wrong cap. - - -

-const ENotAuthorized: u64 = 2;
-
- - - - - -The balance is too low to perform the action. - - -

-const EBalanceTooLow: u64 = 3;
-
- - - - - -The balance is not zero when trying to confirm with -TransferPolicyCap. - - -

-const ECantConsumeBalance: u64 = 5;
-
- - - - - -Rule is trying to access a missing config (with type). - - -

-const ENoConfig: u64 = 6;
-
- - - - - -The rule was not approved. - - -

-const ENotApproved: u64 = 1;
-
- - - - - -The balance is not zero. - - -

-const ENotZero: u64 = 4;
-
- - - - - -The action is not allowed (defined) in the policy. - - -

-const EUnknownAction: u64 = 0;
-
- - - - - -Using -confirm_request_mut without -spent_balance. Immutable version -of the function must be used instead. - - -

-const EUseImmutableConfirm: u64 = 7;
-
- - - - - -A Tag for the -from_coin action. - - -

-const FROM_COIN: vector<u8> = [102, 114, 111, 109, 95, 99, 111, 105, 110];
-
- - - - - -A Tag for the -spend action. - - -

-const SPEND: vector<u8> = [115, 112, 101, 110, 100];
-
- - - - - -A Tag for the -to_coin action. - - -

-const TO_COIN: vector<u8> = [116, 111, 95, 99, 111, 105, 110];
-
- - - - - -A Tag for the -transfer action. - - -

-const TRANSFER: vector<u8> = [116, 114, 97, 110, 115, 102, 101, 114];
-
- - - - - -## Function `new_policy` - -Create a new -TokenPolicy and a matching -TokenPolicyCap. -The -TokenPolicy must then be shared using the -share_policy method. - - -TreasuryCap guarantees full ownership over the currency, and is unique, -hence it is safe to use it for authorization. - - -

-public fun new_policy<T>(_treasury_cap: &coin::TreasuryCap<T>, ctx: &mut tx_context::TxContext): (token::TokenPolicy<T>, token::TokenPolicyCap<T>)
-
- - - -
-Implementation - - -

-public fun new_policy<T>(
-    _treasury_cap: &TreasuryCap<T>, ctx: &mut TxContext
-): (TokenPolicy<T>, TokenPolicyCap<T>) \{
-    let policy = TokenPolicy \{
-        id: object::new(ctx),
-        spent_balance: balance::zero(),
-        rules: vec_map::empty()
-    };
-
-    let cap = TokenPolicyCap \{
-        id: object::new(ctx),
-        `for`: object::id(&policy)
-    };
-
-    (policy, cap)
-}
-
- - - -
- - - -## Function `share_policy` - -Share the -TokenPolicy. Due to -key-only restriction, it must be -shared after initialization. - - -

-public fun share_policy<T>(policy: token::TokenPolicy<T>)
-
- - - -
-Implementation - - -

-public fun share_policy<T>(policy: TokenPolicy<T>) \{
-    event::emit(TokenPolicyCreated<T> \{
-        id: object::id(&policy),
-        is_mutable: true,
-    });
-
-    transfer::share_object(policy)
-}
-
- - - -
- - - -## Function `transfer` - -Transfer a -Token to a -recipient. Creates an -ActionRequest for the -"transfer" action. The -ActionRequest contains the -recipient field -to be used in verification. - - -

-public fun transfer<T>(t: token::Token<T>, recipient: address, ctx: &mut tx_context::TxContext): token::ActionRequest<T>
-
- - - -
-Implementation - - -

-public fun transfer<T>(
-    t: Token<T>, recipient: address, ctx: &mut TxContext
-): ActionRequest<T> \{
-    let amount = t.balance.value();
-    transfer::transfer(t, recipient);
-
-    new_request(
-        transfer_action(),
-        amount,
-        option::some(recipient),
-        option::none(),
-        ctx
-    )
-}
-
- - - -
- - - -## Function `spend` - -Spend a -Token by unwrapping it and storing the -Balance in the - -ActionRequest for the "spend" action. The -ActionRequest contains -the -spent_balance field to be used in verification. - -Spend action requires -confirm_request_mut to be called to confirm the -request and join the spent balance with the -TokenPolicy.spent_balance. - - -

-public fun spend<T>(t: token::Token<T>, ctx: &mut tx_context::TxContext): token::ActionRequest<T>
-
- - - -
-Implementation - - -

-public fun spend<T>(t: Token<T>, ctx: &mut TxContext): ActionRequest<T> \{
-    let Token \{ id, balance } = t;
-    id.delete();
-
-    new_request(
-        spend_action(),
-        balance.value(),
-        option::none(),
-        option::some(balance),
-        ctx
-    )
-}
-
- - - -
- - - -## Function `to_coin` - -Convert -Token into an open -Coin. Creates an -ActionRequest for the -"to_coin" action. - - -

-public fun to_coin<T>(t: token::Token<T>, ctx: &mut tx_context::TxContext): (coin::Coin<T>, token::ActionRequest<T>)
-
- - - -
-Implementation - - -

-public fun to_coin<T>(
-    t: Token<T>, ctx: &mut TxContext
-): (Coin<T>, ActionRequest<T>) \{
-    let Token \{ id, balance } = t;
-    let amount = balance.value();
-    id.delete();
-
-    (
-        balance.into_coin(ctx),
-        new_request(
-            to_coin_action(),
-            amount,
-            option::none(),
-            option::none(),
-            ctx
-        )
-    )
-}
-
- - - -
- - - -## Function `from_coin` - -Convert an open -Coin into a -Token. Creates an -ActionRequest for -the "from_coin" action. - - -

-public fun from_coin<T>(coin: coin::Coin<T>, ctx: &mut tx_context::TxContext): (token::Token<T>, token::ActionRequest<T>)
-
- - - -
-Implementation - - -

-public fun from_coin<T>(
-    coin: Coin<T>, ctx: &mut TxContext
-): (Token<T>, ActionRequest<T>) \{
-    let amount = coin.value();
-    let token = Token \{
-        id: object::new(ctx),
-        balance: coin.into_balance()
-    };
-
-    (
-        token,
-        new_request(
-            from_coin_action(),
-            amount,
-            option::none(),
-            option::none(),
-            ctx
-        )
-    )
-}
-
- - - -
- - - -## Function `join` - -Join two -Tokens into one, always available. - - -

-public fun join<T>(token: &mut token::Token<T>, another: token::Token<T>)
-
- - - -
-Implementation - - -

-public fun join<T>(token: &mut Token<T>, another: Token<T>) \{
-    let Token \{ id, balance } = another;
-    token.balance.join(balance);
-    id.delete();
-}
-
- - - -
- - - -## Function `split` - -Split a -Token with -amount. -Aborts if the -Token.balance is lower than -amount. - - -

-public fun split<T>(token: &mut token::Token<T>, amount: u64, ctx: &mut tx_context::TxContext): token::Token<T>
-
- - - -
-Implementation - - -

-public fun split<T>(
-    token: &mut Token<T>, amount: u64, ctx: &mut TxContext
-): Token<T> \{
-    assert!(token.balance.value() >= amount, EBalanceTooLow);
-    Token \{
-        id: object::new(ctx),
-        balance: token.balance.split(amount),
-    }
-}
-
- - - -
- - - -## Function `zero` - -Create a zero -Token. - - -

-public fun zero<T>(ctx: &mut tx_context::TxContext): token::Token<T>
-
- - - -
-Implementation - - -

-public fun zero<T>(ctx: &mut TxContext): Token<T> \{
-    Token \{
-        id: object::new(ctx),
-        balance: balance::zero(),
-    }
-}
-
- - - -
- - - -## Function `destroy_zero` - -Destroy an empty -Token, fails if the balance is non-zero. -Aborts if the -Token.balance is not zero. - - -

-public fun destroy_zero<T>(token: token::Token<T>)
-
- - - -
-Implementation - - -

-public fun destroy_zero<T>(token: Token<T>) \{
-    let Token \{ id, balance } = token;
-    assert!(balance.value() == 0, ENotZero);
-    balance.destroy_zero();
-    id.delete();
-}
-
- - - -
- - - -## Function `keep` - -Transfer the -Token to the transaction sender. - - -

-public fun keep<T>(token: token::Token<T>, ctx: &mut tx_context::TxContext)
-
- - - -
-Implementation - - -

-public fun keep<T>(token: Token<T>, ctx: &mut TxContext) \{
-    transfer::transfer(token, ctx.sender())
-}
-
- - - -
- - - -## Function `new_request` - -Create a new -ActionRequest. -Publicly available method to allow for custom actions. - - -

-public fun new_request<T>(name: string::String, amount: u64, recipient: option::Option<address>, spent_balance: option::Option<balance::Balance<T>>, ctx: &tx_context::TxContext): token::ActionRequest<T>
-
- - - -
-Implementation - - -

-public fun new_request<T>(
-    name: String,
-    amount: u64,
-    recipient: Option<address>,
-    spent_balance: Option<Balance<T>>,
-    ctx: &TxContext
-): ActionRequest<T> \{
-    ActionRequest \{
-        name,
-        amount,
-        recipient,
-        spent_balance,
-        sender: ctx.sender(),
-        approvals: vec_set::empty(),
-    }
-}
-
- - - -
- - - -## Function `confirm_request` - -Confirm the request against the -TokenPolicy and return the parameters -of the request: (Name, Amount, Sender, Recipient). - -Cannot be used for -spend and similar actions that deliver -spent_balance -to the -TokenPolicy. For those actions use -confirm_request_mut. - -Aborts if: -- the action is not allowed (missing record in -rules) -- action contains -spent_balance (use -confirm_request_mut) -- the -ActionRequest does not meet the -TokenPolicy rules for the action - - -

-public fun confirm_request<T>(policy: &token::TokenPolicy<T>, request: token::ActionRequest<T>, _ctx: &mut tx_context::TxContext): (string::String, u64, address, option::Option<address>)
-
- - - -
-Implementation - - -

-public fun confirm_request<T>(
-    policy: &TokenPolicy<T>,
-    request: ActionRequest<T>,
-    _ctx: &mut TxContext
-): (String, u64, address, Option<address>) \{
-    assert!(request.spent_balance.is_none(), ECantConsumeBalance);
-    assert!(policy.rules.contains(&request.name), EUnknownAction);
-
-    let ActionRequest \{
-        name, approvals,
-        spent_balance,
-        amount, sender, recipient,
-    } = request;
-
-    spent_balance.destroy_none();
-
-    let rules = &(*policy.rules.get(&name)).into_keys();
-    let rules_len = rules.length();
-    let mut i = 0;
-
-    while (i < rules_len) \{
-        let rule = &rules[i];
-        assert!(approvals.contains(rule), ENotApproved);
-        i = i + 1;
-    };
-
-    (name, amount, sender, recipient)
-}
-
- - - -
- - - -## Function `confirm_request_mut` - -Confirm the request against the -TokenPolicy and return the parameters -of the request: (Name, Amount, Sender, Recipient). - -Unlike -confirm_request this function requires mutable access to the - -TokenPolicy and must be used on -spend action. After dealing with the -spent balance it calls -confirm_request internally. - -See -confirm_request for the list of abort conditions. - - -

-public fun confirm_request_mut<T>(policy: &mut token::TokenPolicy<T>, request: token::ActionRequest<T>, ctx: &mut tx_context::TxContext): (string::String, u64, address, option::Option<address>)
-
- - - -
-Implementation - - -

-public fun confirm_request_mut<T>(
-    policy: &mut TokenPolicy<T>,
-    mut request: ActionRequest<T>,
-    ctx: &mut TxContext
-): (String, u64, address, Option<address>) \{
-    assert!(policy.rules.contains(&request.name), EUnknownAction);
-    assert!(request.spent_balance.is_some(), EUseImmutableConfirm);
-
-    policy.spent_balance.join(request.spent_balance.extract());
-
-    confirm_request(policy, request, ctx)
-}
-
- - - -
- - - -## Function `confirm_with_policy_cap` - -Confirm an -ActionRequest as the -TokenPolicyCap owner. This function -allows -TokenPolicy owner to perform Capability-gated actions ignoring -the ruleset specified in the -TokenPolicy. - -Aborts if request contains -spent_balance due to inability of the - -TokenPolicyCap to decrease supply. For scenarios like this a - -TreasuryCap is required (see -confirm_with_treasury_cap). - - -

-public fun confirm_with_policy_cap<T>(_policy_cap: &token::TokenPolicyCap<T>, request: token::ActionRequest<T>, _ctx: &mut tx_context::TxContext): (string::String, u64, address, option::Option<address>)
-
- - - -
-Implementation - - -

-public fun confirm_with_policy_cap<T>(
-    _policy_cap: &TokenPolicyCap<T>,
-    request: ActionRequest<T>,
-    _ctx: &mut TxContext
-): (String, u64, address, Option<address>) \{
-    assert!(request.spent_balance.is_none(), ECantConsumeBalance);
-
-    let ActionRequest \{
-        name, amount, sender, recipient, approvals: _, spent_balance
-    } = request;
-
-    spent_balance.destroy_none();
-
-    (name, amount, sender, recipient)
-}
-
- - - -
- - - -## Function `confirm_with_treasury_cap` - -Confirm an -ActionRequest as the -TreasuryCap owner. This function -allows -TreasuryCap owner to perform Capability-gated actions ignoring -the ruleset specified in the -TokenPolicy. - -Unlike -confirm_with_policy_cap this function allows -spent_balance -to be consumed, decreasing the -total_supply of the -Token. - - -

-public fun confirm_with_treasury_cap<T>(treasury_cap: &mut coin::TreasuryCap<T>, request: token::ActionRequest<T>, _ctx: &mut tx_context::TxContext): (string::String, u64, address, option::Option<address>)
-
- - - -
-Implementation - - -

-public fun confirm_with_treasury_cap<T>(
-    treasury_cap: &mut TreasuryCap<T>,
-    request: ActionRequest<T>,
-    _ctx: &mut TxContext
-): (String, u64, address, Option<address>) \{
-    let ActionRequest \{
-        name, amount, sender, recipient, approvals: _,
-        spent_balance
-    } = request;
-
-    if (spent_balance.is_some()) \{
-        treasury_cap.supply_mut().decrease_supply(spent_balance.destroy_some());
-    } else \{
-        spent_balance.destroy_none();
-    };
-
-    (name, amount, sender, recipient)
-}
-
- - - -
- - - -## Function `add_approval` - -Add an "approval" to the -ActionRequest by providing a Witness. -Intended to be used by Rules to add their own approvals, however, can -be used to add arbitrary approvals to the request (not only the ones -required by the -TokenPolicy). - - -

-public fun add_approval<T, W: drop>(_t: W, request: &mut token::ActionRequest<T>, _ctx: &mut tx_context::TxContext)
-
- - - -
-Implementation - - -

-public fun add_approval<T, W: drop>(
-    _t: W, request: &mut ActionRequest<T>, _ctx: &mut TxContext
-) \{
-    request.approvals.insert(type_name::get<W>())
-}
-
- - - -
- - - -## Function `add_rule_config` - -Add a -Config for a -Rule in the -TokenPolicy. Rule configuration is -independent from the -TokenPolicy.rules and needs to be managed by the -Rule itself. Configuration is stored per -Rule and not per -Rule per - -Action to allow reuse in different actions. - -- Rule witness guarantees that the -Config is approved by the Rule. -- -TokenPolicyCap guarantees that the -Config setup is initiated by -the -TokenPolicy owner. - - -

-public fun add_rule_config<T, Rule: drop, Config: store>(_rule: Rule, self: &mut token::TokenPolicy<T>, cap: &token::TokenPolicyCap<T>, config: Config, _ctx: &mut tx_context::TxContext)
-
- - - -
-Implementation - - -

-public fun add_rule_config<T, Rule: drop, Config: store>(
-    _rule: Rule,
-    self: &mut TokenPolicy<T>,
-    cap: &TokenPolicyCap<T>,
-    config: Config,
-    _ctx: &mut TxContext
-) \{
-    assert!(object::id(self) == cap.`for`, ENotAuthorized);
-    df::add(&mut self.id, key<Rule>(), config)
-}
-
- - - -
- - - -## Function `rule_config` - -Get a -Config for a -Rule in the -TokenPolicy. Requires -Rule -witness, hence can only be read by the -Rule itself. This requirement -guarantees safety of the stored -Config and allows for simpler dynamic -field management inside the Rule Config (custom type keys are not needed -for access gating). - -Aborts if the Config is not present. - - -

-public fun rule_config<T, Rule: drop, Config: store>(_rule: Rule, self: &token::TokenPolicy<T>): &Config
-
- - - -
-Implementation - - -

-public fun rule_config<T, Rule: drop, Config: store>(
-    _rule: Rule, self: &TokenPolicy<T>
-): &Config \{
-    assert!(has_rule_config_with_type<T, Rule, Config>(self), ENoConfig);
-    df::borrow(&self.id, key<Rule>())
-}
-
- - - -
- - - -## Function `rule_config_mut` - -Get mutable access to the -Config for a -Rule in the -TokenPolicy. -Requires -Rule witness, hence can only be read by the -Rule itself, -as well as -TokenPolicyCap to guarantee that the -TokenPolicy owner -is the one who initiated the -Config modification. - -Aborts if: -- the Config is not present -- -TokenPolicyCap is not matching the -TokenPolicy - - -

-public fun rule_config_mut<T, Rule: drop, Config: store>(_rule: Rule, self: &mut token::TokenPolicy<T>, cap: &token::TokenPolicyCap<T>): &mut Config
-
- - - -
-Implementation - - -

-public fun rule_config_mut<T, Rule: drop, Config: store>(
-    _rule: Rule, self: &mut TokenPolicy<T>, cap: &TokenPolicyCap<T>
-): &mut Config \{
-    assert!(has_rule_config_with_type<T, Rule, Config>(self), ENoConfig);
-    assert!(object::id(self) == cap.`for`, ENotAuthorized);
-    df::borrow_mut(&mut self.id, key<Rule>())
-}
-
- - - -
- - - -## Function `remove_rule_config` - -Remove a -Config for a -Rule in the -TokenPolicy. -Unlike the -add_rule_config, this function does not require a -Rule -witness, hence can be performed by the -TokenPolicy owner on their own. - -Rules need to make sure that the -Config is present when performing -verification of the -ActionRequest. - -Aborts if: -- the Config is not present -- -TokenPolicyCap is not matching the -TokenPolicy - - -

-public fun remove_rule_config<T, Rule, Config: store>(self: &mut token::TokenPolicy<T>, cap: &token::TokenPolicyCap<T>, _ctx: &mut tx_context::TxContext): Config
-
- - - -
-Implementation - - -

-public fun remove_rule_config<T, Rule, Config: store>(
-    self: &mut TokenPolicy<T>,
-    cap: &TokenPolicyCap<T>,
-    _ctx: &mut TxContext
-): Config \{
-    assert!(has_rule_config_with_type<T, Rule, Config>(self), ENoConfig);
-    assert!(object::id(self) == cap.`for`, ENotAuthorized);
-    df::remove(&mut self.id, key<Rule>())
-}
-
- - - -
- - - -## Function `has_rule_config` - -Check if a config for a -Rule is set in the -TokenPolicy without -checking the type of the -Config. - - -

-public fun has_rule_config<T, Rule>(self: &token::TokenPolicy<T>): bool
-
- - - -
-Implementation - - -

-public fun has_rule_config<T, Rule>(self: &TokenPolicy<T>): bool \{
-    df::exists_<RuleKey<Rule>>(&self.id, key<Rule>())
-}
-
- - - -
- - - -## Function `has_rule_config_with_type` - -Check if a -Config for a -Rule is set in the -TokenPolicy and that -it matches the type provided. - - -

-public fun has_rule_config_with_type<T, Rule, Config: store>(self: &token::TokenPolicy<T>): bool
-
- - - -
-Implementation - - -

-public fun has_rule_config_with_type<T, Rule, Config: store>(
-    self: &TokenPolicy<T>
-): bool \{
-    df::exists_with_type<RuleKey<Rule>, Config>(&self.id, key<Rule>())
-}
-
- - - -
- - - -## Function `allow` - -Allows an -action to be performed on the -Token freely by adding an -empty set of -Rules for the -action. - -Aborts if the -TokenPolicyCap is not matching the -TokenPolicy. - - -

-public fun allow<T>(self: &mut token::TokenPolicy<T>, cap: &token::TokenPolicyCap<T>, action: string::String, _ctx: &mut tx_context::TxContext)
-
- - - -
-Implementation - - -

-public fun allow<T>(
-    self: &mut TokenPolicy<T>,
-    cap: &TokenPolicyCap<T>,
-    action: String,
-    _ctx: &mut TxContext
-) \{
-    assert!(object::id(self) == cap.`for`, ENotAuthorized);
-    self.rules.insert(action, vec_set::empty());
-}
-
- - - -
- - - -## Function `disallow` - -Completely disallows an -action on the -Token by removing the record -from the -TokenPolicy.rules. - -Aborts if the -TokenPolicyCap is not matching the -TokenPolicy. - - -

-public fun disallow<T>(self: &mut token::TokenPolicy<T>, cap: &token::TokenPolicyCap<T>, action: string::String, _ctx: &mut tx_context::TxContext)
-
- - - -
-Implementation - - -

-public fun disallow<T>(
-    self: &mut TokenPolicy<T>,
-    cap: &TokenPolicyCap<T>,
-    action: String,
-    _ctx: &mut TxContext
-) \{
-    assert!(object::id(self) == cap.`for`, ENotAuthorized);
-    self.rules.remove(&action);
-}
-
- - - -
- - - -## Function `add_rule_for_action` - -Adds a Rule for an action with -name in the -TokenPolicy. - -Aborts if the -TokenPolicyCap is not matching the -TokenPolicy. - - -

-public fun add_rule_for_action<T, Rule: drop>(self: &mut token::TokenPolicy<T>, cap: &token::TokenPolicyCap<T>, action: string::String, ctx: &mut tx_context::TxContext)
-
- - - -
-Implementation - - -

-public fun add_rule_for_action<T, Rule: drop>(
-    self: &mut TokenPolicy<T>,
-    cap: &TokenPolicyCap<T>,
-    action: String,
-    ctx: &mut TxContext
-) \{
-    assert!(object::id(self) == cap.`for`, ENotAuthorized);
-    if (!self.rules.contains(&action)) \{
-        allow(self, cap, action, ctx);
-    };
-
-    self.rules.get_mut(&action).insert(type_name::get<Rule>())
-}
-
- - - -
- - - -## Function `remove_rule_for_action` - -Removes a rule for an action with -name in the -TokenPolicy. Returns -the config object to be handled by the sender (or a Rule itself). - -Aborts if the -TokenPolicyCap is not matching the -TokenPolicy. - - -

-public fun remove_rule_for_action<T, Rule: drop>(self: &mut token::TokenPolicy<T>, cap: &token::TokenPolicyCap<T>, action: string::String, _ctx: &mut tx_context::TxContext)
-
- - - -
-Implementation - - -

-public fun remove_rule_for_action<T, Rule: drop>(
-    self: &mut TokenPolicy<T>,
-    cap: &TokenPolicyCap<T>,
-    action: String,
-    _ctx: &mut TxContext
-) \{
-    assert!(object::id(self) == cap.`for`, ENotAuthorized);
-
-    self.rules.get_mut(&action).remove(&type_name::get<Rule>())
-}
-
- - - -
- - - -## Function `mint` - -Mint a -Token with a given -amount using the -TreasuryCap. - - -

-public fun mint<T>(cap: &mut coin::TreasuryCap<T>, amount: u64, ctx: &mut tx_context::TxContext): token::Token<T>
-
- - - -
-Implementation - - -

-public fun mint<T>(
-    cap: &mut TreasuryCap<T>, amount: u64, ctx: &mut TxContext
-): Token<T> \{
-    let balance = cap.supply_mut().increase_supply(amount);
-    Token \{ id: object::new(ctx), balance }
-}
-
- - - -
- - - -## Function `burn` - -Burn a -Token using the -TreasuryCap. - - -

-public fun burn<T>(cap: &mut coin::TreasuryCap<T>, token: token::Token<T>)
-
- - - -
-Implementation - - -

-public fun burn<T>(cap: &mut TreasuryCap<T>, token: Token<T>) \{
-    let Token \{ id, balance } = token;
-    cap.supply_mut().decrease_supply(balance);
-    id.delete();
-}
-
- - - -
- - - -## Function `flush` - -Flush the -TokenPolicy.spent_balance into the -TreasuryCap. This -action is only available to the -TreasuryCap owner. - - -

-public fun flush<T>(self: &mut token::TokenPolicy<T>, cap: &mut coin::TreasuryCap<T>, _ctx: &mut tx_context::TxContext): u64
-
- - - -
-Implementation - - -

-public fun flush<T>(
-    self: &mut TokenPolicy<T>,
-    cap: &mut TreasuryCap<T>,
-    _ctx: &mut TxContext
-): u64 \{
-    let amount = self.spent_balance.value();
-    let balance = self.spent_balance.split(amount);
-    cap.supply_mut().decrease_supply(balance)
-}
-
- - - -
- - - -## Function `is_allowed` - -Check whether an action is present in the rules VecMap. - - -

-public fun is_allowed<T>(self: &token::TokenPolicy<T>, action: &string::String): bool
-
- - - -
-Implementation - - -

-public fun is_allowed<T>(self: &TokenPolicy<T>, action: &String): bool \{
-    self.rules.contains(action)
-}
-
- - - -
- - - -## Function `rules` - -Returns the rules required for a specific action. - - -

-public fun rules<T>(self: &token::TokenPolicy<T>, action: &string::String): vec_set::VecSet<type_name::TypeName>
-
- - - -
-Implementation - - -

-public fun rules<T>(
-    self: &TokenPolicy<T>, action: &String
-): VecSet<TypeName> \{
-    *self.rules.get(action)
-}
-
- - - -
- - - -## Function `spent_balance` - -Returns the -spent_balance of the -TokenPolicy. - - -

-public fun spent_balance<T>(self: &token::TokenPolicy<T>): u64
-
- - - -
-Implementation - - -

-public fun spent_balance<T>(self: &TokenPolicy<T>): u64 \{
-    self.spent_balance.value()
-}
-
- - - -
- - - -## Function `value` - -Returns the -balance of the -Token. - - -

-public fun value<T>(t: &token::Token<T>): u64
-
- - - -
-Implementation - - -

-public fun value<T>(t: &Token<T>): u64 \{
-    t.balance.value()
-}
-
- - - -
- - - -## Function `transfer_action` - -Name of the Transfer action. - - -

-public fun transfer_action(): string::String
-
- - - -
-Implementation - - -

-public fun transfer_action(): String \{
-    let transfer_str = TRANSFER;
-    transfer_str.to_string()
-}
-
- - - -
- - - -## Function `spend_action` - -Name of the -Spend action. - - -

-public fun spend_action(): string::String
-
- - - -
-Implementation - - -

-public fun spend_action(): String \{
-    let spend_str = SPEND;
-    spend_str.to_string()
-}
-
- - - -
- - - -## Function `to_coin_action` - -Name of the -ToCoin action. - - -

-public fun to_coin_action(): string::String
-
- - - -
-Implementation - - -

-public fun to_coin_action(): String \{
-    let to_coin_str = TO_COIN;
-    to_coin_str.to_string()
-}
-
- - - -
- - - -## Function `from_coin_action` - -Name of the -FromCoin action. - - -

-public fun from_coin_action(): string::String
-
- - - -
-Implementation - - -

-public fun from_coin_action(): String \{
-    let from_coin_str = FROM_COIN;
-    from_coin_str.to_string()
-}
-
- - - -
- - - -## Function `action` - -The Action in the -ActionRequest. - - -

-public fun action<T>(self: &token::ActionRequest<T>): string::String
-
- - - -
-Implementation - - -

-public fun action<T>(self: &ActionRequest<T>): String \{ self.name }
-
- - - -
- - - -## Function `amount` - -Amount of the -ActionRequest. - - -

-public fun amount<T>(self: &token::ActionRequest<T>): u64
-
- - - -
-Implementation - - -

-public fun amount<T>(self: &ActionRequest<T>): u64 \{ self.amount }
-
- - - -
- - - -## Function `sender` - -Sender of the -ActionRequest. - - -

-public fun sender<T>(self: &token::ActionRequest<T>): address
-
- - - -
-Implementation - - -

-public fun sender<T>(self: &ActionRequest<T>): address \{ self.sender }
-
- - - -
- - - -## Function `recipient` - -Recipient of the -ActionRequest. - - -

-public fun recipient<T>(self: &token::ActionRequest<T>): option::Option<address>
-
- - - -
-Implementation - - -

-public fun recipient<T>(self: &ActionRequest<T>): Option<address> \{
-    self.recipient
-}
-
- - - -
- - - -## Function `approvals` - -Approvals of the -ActionRequest. - - -

-public fun approvals<T>(self: &token::ActionRequest<T>): vec_set::VecSet<type_name::TypeName>
-
- - - -
-Implementation - - -

-public fun approvals<T>(self: &ActionRequest<T>): VecSet<TypeName> \{
-    self.approvals
-}
-
- - - -
- - - -## Function `spent` - -Burned balance of the -ActionRequest. - - -

-public fun spent<T>(self: &token::ActionRequest<T>): option::Option<u64>
-
- - - -
-Implementation - - -

-public fun spent<T>(self: &ActionRequest<T>): Option<u64> \{
-    if (self.spent_balance.is_some()) \{
-        option::some(self.spent_balance.borrow().value())
-    } else \{
-        option::none()
-    }
-}
-
- - - -
- - - -## Function `key` - -Create a new -RuleKey for a -Rule. The -is_protected field is kept -for potential future use, if Rules were to have a freely modifiable -storage as addition / replacement for the -Config system. - -The goal of -is_protected is to potentially allow Rules store a mutable -version of their configuration and mutate state on user action. - - -

-fun key<Rule>(): token::RuleKey<Rule>
-
- - - -
-Implementation - - -

-fun key<Rule>(): RuleKey<Rule> \{ RuleKey \{ is_protected: true } }
-
- - - -
diff --git a/crates/iota-framework/docs/iota-framework/transfer.mdx b/crates/iota-framework/docs/iota-framework/transfer.mdx deleted file mode 100644 index ecf550ac916..00000000000 --- a/crates/iota-framework/docs/iota-framework/transfer.mdx +++ /dev/null @@ -1,571 +0,0 @@ ---- -title: Module `0x2::transfer` ---- -import Link from '@docusaurus/Link'; - - - - -- [Struct `Receiving`](#0x2_transfer_Receiving) -- [Constants](#@Constants_0) -- [Function `transfer`](#0x2_transfer_transfer) -- [Function `public_transfer`](#0x2_transfer_public_transfer) -- [Function `freeze_object`](#0x2_transfer_freeze_object) -- [Function `public_freeze_object`](#0x2_transfer_public_freeze_object) -- [Function `share_object`](#0x2_transfer_share_object) -- [Function `public_share_object`](#0x2_transfer_public_share_object) -- [Function `receive`](#0x2_transfer_receive) -- [Function `public_receive`](#0x2_transfer_public_receive) -- [Function `receiving_object_id`](#0x2_transfer_receiving_object_id) -- [Function `freeze_object_impl`](#0x2_transfer_freeze_object_impl) -- [Function `share_object_impl`](#0x2_transfer_share_object_impl) -- [Function `transfer_impl`](#0x2_transfer_transfer_impl) -- [Function `receive_impl`](#0x2_transfer_receive_impl) - - -

-use 0x2::object;
-
- - - - - -## Struct `Receiving` - -This represents the ability to -receive an object of type -T. -This type is ephemeral per-transaction and cannot be stored on-chain. -This does not represent the obligation to receive the object that it -references, but simply the ability to receive the object with object ID - -id at version -version if you can prove mutable access to the parent -object during the transaction. -Internals of this struct are opaque outside this module. - - -

-struct Receiving<T: key> has drop
-
- - - -
-Fields - - -
-
- -id: object::ID -
-
- -
-
- -version: u64 -
-
- -
-
- - -
- - - -## Constants - - - - -Serialization of the object failed. - - -

-const EBCSSerializationFailure: u64 = 1;
-
- - - - - -The object being received is not of the expected type. - - -

-const EReceivingObjectTypeMismatch: u64 = 2;
-
- - - - - -Shared an object that was previously created. Shared objects must currently -be constructed in the transaction they are created. - - -

-const ESharedNonNewObject: u64 = 0;
-
- - - - - -Shared object operations such as wrapping, freezing, and converting to owned are not allowed. - - -

-const ESharedObjectOperationNotSupported: u64 = 4;
-
- - - - - -Represents both the case where the object does not exist and the case where the object is not -able to be accessed through the parent that is passed-in. - - -

-const EUnableToReceiveObject: u64 = 3;
-
- - - - - -## Function `transfer` - -Transfer ownership of -obj to -recipient. -obj must have the -key attribute, -which (in turn) ensures that -obj has a globally unique ID. Note that if the recipient -address represents an object ID, the -obj sent will be inaccessible after the transfer -(though they will be retrievable at a future date once new features are added). -This function has custom rules performed by the Iota Move bytecode verifier that ensures -that -T is an object defined in the module where -transfer is invoked. Use - -public_transfer to transfer an object with -store outside of its module. - - -

-public fun transfer<T: key>(obj: T, recipient: address)
-
- - - -
-Implementation - - -

-public fun transfer<T: key>(obj: T, recipient: address) \{
-    transfer_impl(obj, recipient)
-}
-
- - - -
- - - -## Function `public_transfer` - -Transfer ownership of -obj to -recipient. -obj must have the -key attribute, -which (in turn) ensures that -obj has a globally unique ID. Note that if the recipient -address represents an object ID, the -obj sent will be inaccessible after the transfer -(though they will be retrievable at a future date once new features are added). -The object must have -store to be transferred outside of its module. - - -

-public fun public_transfer<T: store, key>(obj: T, recipient: address)
-
- - - -
-Implementation - - -

-public fun public_transfer<T: key + store>(obj: T, recipient: address) \{
-    transfer_impl(obj, recipient)
-}
-
- - - -
- - - -## Function `freeze_object` - -Freeze -obj. After freezing -obj becomes immutable and can no longer be transferred or -mutated. -This function has custom rules performed by the Iota Move bytecode verifier that ensures -that -T is an object defined in the module where -freeze_object is invoked. Use - -public_freeze_object to freeze an object with -store outside of its module. - - -

-public fun freeze_object<T: key>(obj: T)
-
- - - -
-Implementation - - -

-public fun freeze_object<T: key>(obj: T) \{
-    freeze_object_impl(obj)
-}
-
- - - -
- - - -## Function `public_freeze_object` - -Freeze -obj. After freezing -obj becomes immutable and can no longer be transferred or -mutated. -The object must have -store to be frozen outside of its module. - - -

-public fun public_freeze_object<T: store, key>(obj: T)
-
- - - -
-Implementation - - -

-public fun public_freeze_object<T: key + store>(obj: T) \{
-    freeze_object_impl(obj)
-}
-
- - - -
- - - -## Function `share_object` - -Turn the given object into a mutable shared object that everyone can access and mutate. -This is irreversible, i.e. once an object is shared, it will stay shared forever. -Aborts with -ESharedNonNewObject of the object being shared was not created in this -transaction. This restriction may be relaxed in the future. -This function has custom rules performed by the Iota Move bytecode verifier that ensures -that -T is an object defined in the module where -share_object is invoked. Use - -public_share_object to share an object with -store outside of its module. - - -

-public fun share_object<T: key>(obj: T)
-
- - - -
-Implementation - - -

-public fun share_object<T: key>(obj: T) \{
-    share_object_impl(obj)
-}
-
- - - -
- - - -## Function `public_share_object` - -Turn the given object into a mutable shared object that everyone can access and mutate. -This is irreversible, i.e. once an object is shared, it will stay shared forever. -Aborts with -ESharedNonNewObject of the object being shared was not created in this -transaction. This restriction may be relaxed in the future. -The object must have -store to be shared outside of its module. - - -

-public fun public_share_object<T: store, key>(obj: T)
-
- - - -
-Implementation - - -

-public fun public_share_object<T: key + store>(obj: T) \{
-    share_object_impl(obj)
-}
-
- - - -
- - - -## Function `receive` - -Given mutable (i.e., locked) access to the -parent and a -Receiving argument -referencing an object of type -T owned by -parent use the -to_receive -argument to receive and return the referenced owned object of type -T. -This function has custom rules performed by the Iota Move bytecode verifier that ensures -that -T is an object defined in the module where -receive is invoked. Use - -public_receive to receivne an object with -store outside of its module. - - -

-public fun receive<T: key>(parent: &mut object::UID, to_receive: transfer::Receiving<T>): T
-
- - - -
-Implementation - - -

-public fun receive<T: key>(parent: &mut UID, to_receive: Receiving<T>): T \{
-    let Receiving \{
-        id,
-        version,
-    } = to_receive;
-    receive_impl(parent.to_address(), id, version)
-}
-
- - - -
- - - -## Function `public_receive` - -Given mutable (i.e., locked) access to the -parent and a -Receiving argument -referencing an object of type -T owned by -parent use the -to_receive -argument to receive and return the referenced owned object of type -T. -The object must have -store to be received outside of its defining module. - - -

-public fun public_receive<T: store, key>(parent: &mut object::UID, to_receive: transfer::Receiving<T>): T
-
- - - -
-Implementation - - -

-public fun public_receive<T: key + store>(parent: &mut UID, to_receive: Receiving<T>): T \{
-    let Receiving \{
-        id,
-        version,
-    } = to_receive;
-    receive_impl(parent.to_address(), id, version)
-}
-
- - - -
- - - -## Function `receiving_object_id` - -Return the object ID that the given -Receiving argument references. - - -

-public fun receiving_object_id<T: key>(receiving: &transfer::Receiving<T>): object::ID
-
- - - -
-Implementation - - -

-public fun receiving_object_id<T: key>(receiving: &Receiving<T>): ID \{
-    receiving.id
-}
-
- - - -
- - - -## Function `freeze_object_impl` - - - -

-public(friend) fun freeze_object_impl<T: key>(obj: T)
-
- - - -
-Implementation - - -

-public(package) native fun freeze_object_impl<T: key>(obj: T);
-
- - - -
- - - -## Function `share_object_impl` - - - -

-public(friend) fun share_object_impl<T: key>(obj: T)
-
- - - -
-Implementation - - -

-public(package) native fun share_object_impl<T: key>(obj: T);
-
- - - -
- - - -## Function `transfer_impl` - - - -

-public(friend) fun transfer_impl<T: key>(obj: T, recipient: address)
-
- - - -
-Implementation - - -

-public(package) native fun transfer_impl<T: key>(obj: T, recipient: address);
-
- - - -
- - - -## Function `receive_impl` - - - -

-fun receive_impl<T: key>(parent: address, to_receive: object::ID, version: u64): T
-
- - - -
-Implementation - - -

-native fun receive_impl<T: key>(parent: address, to_receive: ID, version: u64): T;
-
- - - -
diff --git a/crates/iota-framework/docs/iota-framework/transfer_policy.mdx b/crates/iota-framework/docs/iota-framework/transfer_policy.mdx deleted file mode 100644 index f9597a2178b..00000000000 --- a/crates/iota-framework/docs/iota-framework/transfer_policy.mdx +++ /dev/null @@ -1,1027 +0,0 @@ ---- -title: Module `0x2::transfer_policy` ---- -import Link from '@docusaurus/Link'; - - -Defines the -TransferPolicy type and the logic to approve -TransferRequests. - -- TransferPolicy - is a highly customizable primitive, which provides an -interface for the type owner to set custom transfer rules for every -deal performed in the -Kiosk or a similar system that integrates with TP. - -- Once a -TransferPolicy<T> is created for and shared (or frozen), the -type -T becomes tradable in -Kiosks. On every purchase operation, a - -TransferRequest is created and needs to be confirmed by the -TransferPolicy -hot potato or transaction will fail. - -- Type owner (creator) can set any Rules as long as the ecosystem supports -them. All of the Rules need to be resolved within a single transaction (eg -pay royalty and pay fixed commission). Once required actions are performed, -the -TransferRequest can be "confirmed" via -confirm_request call. - -- -TransferPolicy aims to be the main interface for creators to control trades -of their types and collect profits if a fee is required on sales. Custom -policies can be removed at any moment, and the change will affect all instances -of the type at once. - - -- [Struct `TransferRequest`](#0x2_transfer_policy_TransferRequest) -- [Resource `TransferPolicy`](#0x2_transfer_policy_TransferPolicy) -- [Resource `TransferPolicyCap`](#0x2_transfer_policy_TransferPolicyCap) -- [Struct `TransferPolicyCreated`](#0x2_transfer_policy_TransferPolicyCreated) -- [Struct `TransferPolicyDestroyed`](#0x2_transfer_policy_TransferPolicyDestroyed) -- [Struct `RuleKey`](#0x2_transfer_policy_RuleKey) -- [Constants](#@Constants_0) -- [Function `new_request`](#0x2_transfer_policy_new_request) -- [Function `new`](#0x2_transfer_policy_new) -- [Function `default`](#0x2_transfer_policy_default) -- [Function `withdraw`](#0x2_transfer_policy_withdraw) -- [Function `destroy_and_withdraw`](#0x2_transfer_policy_destroy_and_withdraw) -- [Function `confirm_request`](#0x2_transfer_policy_confirm_request) -- [Function `add_rule`](#0x2_transfer_policy_add_rule) -- [Function `get_rule`](#0x2_transfer_policy_get_rule) -- [Function `add_to_balance`](#0x2_transfer_policy_add_to_balance) -- [Function `add_receipt`](#0x2_transfer_policy_add_receipt) -- [Function `has_rule`](#0x2_transfer_policy_has_rule) -- [Function `remove_rule`](#0x2_transfer_policy_remove_rule) -- [Function `uid`](#0x2_transfer_policy_uid) -- [Function `uid_mut_as_owner`](#0x2_transfer_policy_uid_mut_as_owner) -- [Function `rules`](#0x2_transfer_policy_rules) -- [Function `item`](#0x2_transfer_policy_item) -- [Function `paid`](#0x2_transfer_policy_paid) -- [Function `from`](#0x2_transfer_policy_from) - - -

-use 0x1::option;
-use 0x1::type_name;
-use 0x2::balance;
-use 0x2::coin;
-use 0x2::dynamic_field;
-use 0x2::event;
-use 0x2::iota;
-use 0x2::object;
-use 0x2::package;
-use 0x2::transfer;
-use 0x2::tx_context;
-use 0x2::vec_set;
-
- - - - - -## Struct `TransferRequest` - -A "Hot Potato" forcing the buyer to get a transfer permission -from the item type ( -T) owner on purchase attempt. - - -

-struct TransferRequest<T>
-
- - - -
-Fields - - -
-
- -item: object::ID -
-
- The ID of the transferred item. Although the -T has no - constraints, the main use case for this module is to work - with Objects. -
-
- -paid: u64 -
-
- Amount of IOTA paid for the item. Can be used to - calculate the fee / transfer policy enforcement. -
-
- -from: object::ID -
-
- The ID of the Kiosk / Safe the object is being sold from. - Can be used by the TransferPolicy implementors. -
-
- -receipts: vec_set::VecSet<type_name::TypeName> -
-
- Collected Receipts. Used to verify that all of the rules - were followed and -TransferRequest can be confirmed. -
-
- - -
- - - -## Resource `TransferPolicy` - -A unique capability that allows the owner of the -T to authorize -transfers. Can only be created with the -Publisher object. Although -there's no limitation to how many policies can be created, for most -of the cases there's no need to create more than one since any of the -policies can be used to confirm the -TransferRequest. - - -

-struct TransferPolicy<T> has store, key
-
- - - -
-Fields - - -
-
- -id: object::UID -
-
- -
-
- -balance: balance::Balance<iota::IOTA> -
-
- The Balance of the -TransferPolicy which collects -IOTA. - By default, transfer policy does not collect anything , and it's - a matter of an implementation of a specific rule - whether to add - to balance and how much. -
-
- -rules: vec_set::VecSet<type_name::TypeName> -
-
- Set of types of attached rules - used to verify -receipts when - a -TransferRequest is received in -confirm_request function. - - Additionally provides a way to look up currently attached Rules. -
-
- - -
- - - -## Resource `TransferPolicyCap` - -A Capability granting the owner permission to add/remove rules as well -as to -withdraw and -destroy_and_withdraw the -TransferPolicy. - - -

-struct TransferPolicyCap<T> has store, key
-
- - - -
-Fields - - -
-
- -id: object::UID -
-
- -
-
- -policy_id: object::ID -
-
- -
-
- - -
- - - -## Struct `TransferPolicyCreated` - -Event that is emitted when a publisher creates a new -TransferPolicyCap -making the discoverability and tracking the supported types easier. - - -

-struct TransferPolicyCreated<T> has copy, drop
-
- - - -
-Fields - - -
-
- -id: object::ID -
-
- -
-
- - -
- - - -## Struct `TransferPolicyDestroyed` - -Event that is emitted when a publisher destroys a -TransferPolicyCap. -Allows for tracking supported policies. - - -

-struct TransferPolicyDestroyed<T> has copy, drop
-
- - - -
-Fields - - -
-
- -id: object::ID -
-
- -
-
- - -
- - - -## Struct `RuleKey` - -Key to store "Rule" configuration for a specific -TransferPolicy. - - -

-struct RuleKey<T: drop> has copy, drop, store
-
- - - -
-Fields - - -
-
- -dummy_field: bool -
-
- -
-
- - -
- - - -## Constants - - - - -Trying to -withdraw more than there is. - - -

-const ENotEnough: u64 = 5;
-
- - - - - -Trying to -withdraw or -close_and_withdraw with a wrong Cap. - - -

-const ENotOwner: u64 = 4;
-
- - - - - -A completed rule is not set in the -TransferPolicy. - - -

-const EIllegalRule: u64 = 1;
-
- - - - - -The number of receipts does not match the -TransferPolicy requirement. - - -

-const EPolicyNotSatisfied: u64 = 0;
-
- - - - - -Attempting to create a Rule that is already set. - - -

-const ERuleAlreadySet: u64 = 3;
-
- - - - - -A Rule is not set. - - -

-const EUnknownRequrement: u64 = 2;
-
- - - - - -## Function `new_request` - -Construct a new -TransferRequest hot potato which requires an -approving action from the creator to be destroyed / resolved. Once -created, it must be confirmed in the -confirm_request call otherwise -the transaction will fail. - - -

-public fun new_request<T>(item: object::ID, paid: u64, from: object::ID): transfer_policy::TransferRequest<T>
-
- - - -
-Implementation - - -

-public fun new_request<T>(
-    item: ID, paid: u64, from: ID
-): TransferRequest<T> \{
-    TransferRequest \{ item, paid, from, receipts: vec_set::empty() }
-}
-
- - - -
- - - -## Function `new` - -Register a type in the Kiosk system and receive a -TransferPolicy and -a -TransferPolicyCap for the type. The -TransferPolicy is required to -confirm kiosk deals for the -T. If there's no -TransferPolicy -available for use, the type can not be traded in kiosks. - - -

-public fun new<T>(pub: &package::Publisher, ctx: &mut tx_context::TxContext): (transfer_policy::TransferPolicy<T>, transfer_policy::TransferPolicyCap<T>)
-
- - - -
-Implementation - - -

-public fun new<T>(
-    pub: &Publisher, ctx: &mut TxContext
-): (TransferPolicy<T>, TransferPolicyCap<T>) \{
-    assert!(package::from_package<T>(pub), 0);
-    let id = object::new(ctx);
-    let policy_id = id.to_inner();
-
-    event::emit(TransferPolicyCreated<T> \{ id: policy_id });
-
-    (
-        TransferPolicy \{ id, rules: vec_set::empty(), balance: balance::zero() },
-        TransferPolicyCap \{ id: object::new(ctx), policy_id }
-    )
-}
-
- - - -
- - - -## Function `default` - -Initialize the Transfer Policy in the default scenario: Create and share -the -TransferPolicy, transfer -TransferPolicyCap to the transaction -sender. - - -

-entry fun default<T>(pub: &package::Publisher, ctx: &mut tx_context::TxContext)
-
- - - -
-Implementation - - -

-entry fun default<T>(pub: &Publisher, ctx: &mut TxContext) \{
-    let (policy, cap) = new<T>(pub, ctx);
-    iota::transfer::share_object(policy);
-    iota::transfer::transfer(cap, ctx.sender());
-}
-
- - - -
- - - -## Function `withdraw` - -Withdraw some amount of profits from the -TransferPolicy. If amount -is not specified, all profits are withdrawn. - - -

-public fun withdraw<T>(self: &mut transfer_policy::TransferPolicy<T>, cap: &transfer_policy::TransferPolicyCap<T>, amount: option::Option<u64>, ctx: &mut tx_context::TxContext): coin::Coin<iota::IOTA>
-
- - - -
-Implementation - - -

-public fun withdraw<T>(
-    self: &mut TransferPolicy<T>,
-    cap: &TransferPolicyCap<T>,
-    amount: Option<u64>,
-    ctx: &mut TxContext
-): Coin<IOTA> \{
-    assert!(object::id(self) == cap.policy_id, ENotOwner);
-
-    let amount = if (amount.is_some()) \{
-        let amt = amount.destroy_some();
-        assert!(amt <= self.balance.value(), ENotEnough);
-        amt
-    } else \{
-        self.balance.value()
-    };
-
-    coin::take(&mut self.balance, amount, ctx)
-}
-
- - - -
- - - -## Function `destroy_and_withdraw` - -Destroy a TransferPolicyCap. -Can be performed by any party as long as they own it. - - -

-public fun destroy_and_withdraw<T>(self: transfer_policy::TransferPolicy<T>, cap: transfer_policy::TransferPolicyCap<T>, ctx: &mut tx_context::TxContext): coin::Coin<iota::IOTA>
-
- - - -
-Implementation - - -

-public fun destroy_and_withdraw<T>(
-    self: TransferPolicy<T>, cap: TransferPolicyCap<T>, ctx: &mut TxContext
-): Coin<IOTA> \{
-    assert!(object::id(&self) == cap.policy_id, ENotOwner);
-
-    let TransferPolicyCap \{ id: cap_id, policy_id } = cap;
-    let TransferPolicy \{ id, rules: _, balance } = self;
-
-    id.delete();
-    cap_id.delete();
-    event::emit(TransferPolicyDestroyed<T> \{ id: policy_id });
-    balance.into_coin(ctx)
-}
-
- - - -
- - - -## Function `confirm_request` - -Allow a -TransferRequest for the type -T. The call is protected -by the type constraint, as only the publisher of the -T can get - -TransferPolicy<T>. - -Note: unless there's a policy for -T to allow transfers, -Kiosk trades will not be possible. - - -

-public fun confirm_request<T>(self: &transfer_policy::TransferPolicy<T>, request: transfer_policy::TransferRequest<T>): (object::ID, u64, object::ID)
-
- - - -
-Implementation - - -

-public fun confirm_request<T>(
-    self: &TransferPolicy<T>, request: TransferRequest<T>
-): (ID, u64, ID) \{
-    let TransferRequest \{ item, paid, from, receipts } = request;
-    let mut completed = receipts.into_keys();
-    let mut total = completed.length();
-
-    assert!(total == self.rules.size(), EPolicyNotSatisfied);
-
-    while (total > 0) \{
-        let rule_type = completed.pop_back();
-        assert!(self.rules.contains(&rule_type), EIllegalRule);
-        total = total - 1;
-    };
-
-    (item, paid, from)
-}
-
- - - -
- - - -## Function `add_rule` - -Add a custom Rule to the -TransferPolicy. Once set, -TransferRequest must -receive a confirmation of the rule executed so the hot potato can be unpacked. - -- T: the type to which `TransferPolicy` is applied. -- Rule: the witness type for the Custom rule -- Config: a custom configuration for the rule - -Config requires -drop to allow creators to remove any policy at any moment, -even if graceful unpacking has not been implemented in a "rule module". - - -

-public fun add_rule<T, Rule: drop, Config: drop, store>(_: Rule, policy: &mut transfer_policy::TransferPolicy<T>, cap: &transfer_policy::TransferPolicyCap<T>, cfg: Config)
-
- - - -
-Implementation - - -

-public fun add_rule<T, Rule: drop, Config: store + drop>(
-    _: Rule, policy: &mut TransferPolicy<T>, cap: &TransferPolicyCap<T>, cfg: Config
-) \{
-    assert!(object::id(policy) == cap.policy_id, ENotOwner);
-    assert!(!has_rule<T, Rule>(policy), ERuleAlreadySet);
-    df::add(&mut policy.id, RuleKey<Rule> \{}, cfg);
-    policy.rules.insert(type_name::get<Rule>())
-}
-
- - - -
- - - -## Function `get_rule` - -Get the custom Config for the Rule (can be only one per "Rule" type). - - -

-public fun get_rule<T, Rule: drop, Config: drop, store>(_: Rule, policy: &transfer_policy::TransferPolicy<T>): &Config
-
- - - -
-Implementation - - -

-public fun get_rule<T, Rule: drop, Config: store + drop>(
-    _: Rule, policy: &TransferPolicy<T>)
-: &Config \{
-    df::borrow(&policy.id, RuleKey<Rule> \{})
-}
-
- - - -
- - - -## Function `add_to_balance` - -Add some -IOTA to the balance of a -TransferPolicy. - - -

-public fun add_to_balance<T, Rule: drop>(_: Rule, policy: &mut transfer_policy::TransferPolicy<T>, coin: coin::Coin<iota::IOTA>)
-
- - - -
-Implementation - - -

-public fun add_to_balance<T, Rule: drop>(
-    _: Rule, policy: &mut TransferPolicy<T>, coin: Coin<IOTA>
-) \{
-    assert!(has_rule<T, Rule>(policy), EUnknownRequrement);
-    coin::put(&mut policy.balance, coin)
-}
-
- - - -
- - - -## Function `add_receipt` - -Adds a -Receipt to the -TransferRequest, unblocking the request and -confirming that the policy requirements are satisfied. - - -

-public fun add_receipt<T, Rule: drop>(_: Rule, request: &mut transfer_policy::TransferRequest<T>)
-
- - - -
-Implementation - - -

-public fun add_receipt<T, Rule: drop>(
-    _: Rule, request: &mut TransferRequest<T>
-) \{
-    request.receipts.insert(type_name::get<Rule>())
-}
-
- - - -
- - - -## Function `has_rule` - -Check whether a custom rule has been added to the -TransferPolicy. - - -

-public fun has_rule<T, Rule: drop>(policy: &transfer_policy::TransferPolicy<T>): bool
-
- - - -
-Implementation - - -

-public fun has_rule<T, Rule: drop>(policy: &TransferPolicy<T>): bool \{
-    df::exists_(&policy.id, RuleKey<Rule> \{})
-}
-
- - - -
- - - -## Function `remove_rule` - -Remove the Rule from the -TransferPolicy. - - -

-public fun remove_rule<T, Rule: drop, Config: drop, store>(policy: &mut transfer_policy::TransferPolicy<T>, cap: &transfer_policy::TransferPolicyCap<T>)
-
- - - -
-Implementation - - -

-public fun remove_rule<T, Rule: drop, Config: store + drop>(
-    policy: &mut TransferPolicy<T>, cap: &TransferPolicyCap<T>
-) \{
-    assert!(object::id(policy) == cap.policy_id, ENotOwner);
-    let _: Config = df::remove(&mut policy.id, RuleKey<Rule> \{});
-    policy.rules.remove(&type_name::get<Rule>());
-}
-
- - - -
- - - -## Function `uid` - -Allows reading custom attachments to the -TransferPolicy if there are any. - - -

-public fun uid<T>(self: &transfer_policy::TransferPolicy<T>): &object::UID
-
- - - -
-Implementation - - -

-public fun uid<T>(self: &TransferPolicy<T>): &UID \{ &self.id }
-
- - - -
- - - -## Function `uid_mut_as_owner` - -Get a mutable reference to the -self.id to enable custom attachments -to the -TransferPolicy. - - -

-public fun uid_mut_as_owner<T>(self: &mut transfer_policy::TransferPolicy<T>, cap: &transfer_policy::TransferPolicyCap<T>): &mut object::UID
-
- - - -
-Implementation - - -

-public fun uid_mut_as_owner<T>(
-    self: &mut TransferPolicy<T>, cap: &TransferPolicyCap<T>,
-): &mut UID \{
-    assert!(object::id(self) == cap.policy_id, ENotOwner);
-    &mut self.id
-}
-
- - - -
- - - -## Function `rules` - -Read the -rules field from the -TransferPolicy. - - -

-public fun rules<T>(self: &transfer_policy::TransferPolicy<T>): &vec_set::VecSet<type_name::TypeName>
-
- - - -
-Implementation - - -

-public fun rules<T>(self: &TransferPolicy<T>): &VecSet<TypeName> \{
-    &self.rules
-}
-
- - - -
- - - -## Function `item` - -Get the -item field of the -TransferRequest. - - -

-public fun item<T>(self: &transfer_policy::TransferRequest<T>): object::ID
-
- - - -
-Implementation - - -

-public fun item<T>(self: &TransferRequest<T>): ID \{ self.item }
-
- - - -
- - - -## Function `paid` - -Get the -paid field of the -TransferRequest. - - -

-public fun paid<T>(self: &transfer_policy::TransferRequest<T>): u64
-
- - - -
-Implementation - - -

-public fun paid<T>(self: &TransferRequest<T>): u64 \{ self.paid }
-
- - - -
- - - -## Function `from` - -Get the -from field of the -TransferRequest. - - -

-public fun from<T>(self: &transfer_policy::TransferRequest<T>): object::ID
-
- - - -
-Implementation - - -

-public fun from<T>(self: &TransferRequest<T>): ID \{ self.from }
-
- - - -
diff --git a/crates/iota-framework/docs/iota-framework/tx_context.mdx b/crates/iota-framework/docs/iota-framework/tx_context.mdx deleted file mode 100644 index 05659737443..00000000000 --- a/crates/iota-framework/docs/iota-framework/tx_context.mdx +++ /dev/null @@ -1,280 +0,0 @@ ---- -title: Module `0x2::tx_context` ---- -import Link from '@docusaurus/Link'; - - - - -- [Struct `TxContext`](#0x2_tx_context_TxContext) -- [Function `sender`](#0x2_tx_context_sender) -- [Function `digest`](#0x2_tx_context_digest) -- [Function `epoch`](#0x2_tx_context_epoch) -- [Function `epoch_timestamp_ms`](#0x2_tx_context_epoch_timestamp_ms) -- [Function `fresh_object_address`](#0x2_tx_context_fresh_object_address) -- [Function `ids_created`](#0x2_tx_context_ids_created) -- [Function `derive_id`](#0x2_tx_context_derive_id) - - -

-
- - - - - -## Struct `TxContext` - -Information about the transaction currently being executed. -This cannot be constructed by a transaction--it is a privileged object created by -the VM and passed in to the entrypoint of the transaction as -&mut TxContext. - - -

-struct TxContext has drop
-
- - - -
-Fields - - -
-
- -sender: address -
-
- The address of the user that signed the current transaction -
-
- -tx_hash: vector<u8> -
-
- Hash of the current transaction -
-
- -epoch: u64 -
-
- The current epoch number -
-
- -epoch_timestamp_ms: u64 -
-
- Timestamp that the epoch started at -
-
- -ids_created: u64 -
-
- Counter recording the number of fresh id's created while executing - this transaction. Always 0 at the start of a transaction -
-
- - -
- - - -## Function `sender` - -Return the address of the user that signed the current -transaction - - -

-public fun sender(self: &tx_context::TxContext): address
-
- - - -
-Implementation - - -

-public fun sender(self: &TxContext): address \{
-    self.sender
-}
-
- - - -
- - - -## Function `digest` - -Return the transaction digest (hash of transaction inputs). -Please do not use as a source of randomness. - - -

-public fun digest(self: &tx_context::TxContext): &vector<u8>
-
- - - -
-Implementation - - -

-public fun digest(self: &TxContext): &vector<u8> \{
-    &self.tx_hash
-}
-
- - - -
- - - -## Function `epoch` - -Return the current epoch - - -

-public fun epoch(self: &tx_context::TxContext): u64
-
- - - -
-Implementation - - -

-public fun epoch(self: &TxContext): u64 \{
-    self.epoch
-}
-
- - - -
- - - -## Function `epoch_timestamp_ms` - -Return the epoch start time as a unix timestamp in milliseconds. - - -

-public fun epoch_timestamp_ms(self: &tx_context::TxContext): u64
-
- - - -
-Implementation - - -

-public fun epoch_timestamp_ms(self: &TxContext): u64 \{
-   self.epoch_timestamp_ms
-}
-
- - - -
- - - -## Function `fresh_object_address` - -Create an -address that has not been used. As it is an object address, it will never -occur as the address for a user. -In other words, the generated address is a globally unique object ID. - - -

-public fun fresh_object_address(ctx: &mut tx_context::TxContext): address
-
- - - -
-Implementation - - -

-public fun fresh_object_address(ctx: &mut TxContext): address \{
-    let ids_created = ctx.ids_created;
-    let id = derive_id(*&ctx.tx_hash, ids_created);
-    ctx.ids_created = ids_created + 1;
-    id
-}
-
- - - -
- - - -## Function `ids_created` - -Return the number of id's created by the current transaction. -Hidden for now, but may expose later - - -

-fun ids_created(self: &tx_context::TxContext): u64
-
- - - -
-Implementation - - -

-fun ids_created(self: &TxContext): u64 \{
-    self.ids_created
-}
-
- - - -
- - - -## Function `derive_id` - -Native function for deriving an ID via hash(tx_hash || ids_created) - - -

-fun derive_id(tx_hash: vector<u8>, ids_created: u64): address
-
- - - -
-Implementation - - -

-native fun derive_id(tx_hash: vector<u8>, ids_created: u64): address;
-
- - - -
diff --git a/crates/iota-framework/docs/iota-framework/types.mdx b/crates/iota-framework/docs/iota-framework/types.mdx deleted file mode 100644 index a35b1f5b705..00000000000 --- a/crates/iota-framework/docs/iota-framework/types.mdx +++ /dev/null @@ -1,42 +0,0 @@ ---- -title: Module `0x2::types` ---- -import Link from '@docusaurus/Link'; - - -Iota types helpers and utilities - - -- [Function `is_one_time_witness`](#0x2_types_is_one_time_witness) - - -

-
- - - - - -## Function `is_one_time_witness` - -Tests if the argument type is a one-time witness, that is a type with only one instantiation -across the entire code base. - - -

-public fun is_one_time_witness<T: drop>(_: &T): bool
-
- - - -
-Implementation - - -

-public native fun is_one_time_witness<T: drop>(_: &T): bool;
-
- - - -
diff --git a/crates/iota-framework/docs/iota-framework/url.mdx b/crates/iota-framework/docs/iota-framework/url.mdx deleted file mode 100644 index f8729e171c3..00000000000 --- a/crates/iota-framework/docs/iota-framework/url.mdx +++ /dev/null @@ -1,164 +0,0 @@ ---- -title: Module `0x2::url` ---- -import Link from '@docusaurus/Link'; - - -URL: standard Uniform Resource Locator string - - -- [Struct `Url`](#0x2_url_Url) -- [Function `new_unsafe`](#0x2_url_new_unsafe) -- [Function `new_unsafe_from_bytes`](#0x2_url_new_unsafe_from_bytes) -- [Function `inner_url`](#0x2_url_inner_url) -- [Function `update`](#0x2_url_update) - - -

-use 0x1::ascii;
-
- - - - - -## Struct `Url` - -Standard Uniform Resource Locator (URL) string. - - -

-struct Url has copy, drop, store
-
- - - -
-Fields - - -
-
- -url: ascii::String -
-
- -
-
- - -
- - - -## Function `new_unsafe` - -Create a -Url, with no validation - - -

-public fun new_unsafe(url: ascii::String): url::Url
-
- - - -
-Implementation - - -

-public fun new_unsafe(url: String): Url \{
-    Url \{ url }
-}
-
- - - -
- - - -## Function `new_unsafe_from_bytes` - -Create a -Url with no validation from bytes -Note: this will abort if -bytes is not valid ASCII - - -

-public fun new_unsafe_from_bytes(bytes: vector<u8>): url::Url
-
- - - -
-Implementation - - -

-public fun new_unsafe_from_bytes(bytes: vector<u8>): Url \{
-    let url = bytes.to_ascii_string();
-    Url \{ url }
-}
-
- - - -
- - - -## Function `inner_url` - -Get inner URL - - -

-public fun inner_url(self: &url::Url): ascii::String
-
- - - -
-Implementation - - -

-public fun inner_url(self: &Url): String\{
-    self.url
-}
-
- - - -
- - - -## Function `update` - -Update the inner URL - - -

-public fun update(self: &mut url::Url, url: ascii::String)
-
- - - -
-Implementation - - -

-public fun update(self: &mut Url, url: String) \{
-    self.url = url;
-}
-
- - - -
diff --git a/crates/iota-framework/docs/iota-framework/vec_map.mdx b/crates/iota-framework/docs/iota-framework/vec_map.mdx deleted file mode 100644 index 0698efe3787..00000000000 --- a/crates/iota-framework/docs/iota-framework/vec_map.mdx +++ /dev/null @@ -1,769 +0,0 @@ ---- -title: Module `0x2::vec_map` ---- -import Link from '@docusaurus/Link'; - - - - -- [Struct `VecMap`](#0x2_vec_map_VecMap) -- [Struct `Entry`](#0x2_vec_map_Entry) -- [Constants](#@Constants_0) -- [Function `empty`](#0x2_vec_map_empty) -- [Function `insert`](#0x2_vec_map_insert) -- [Function `remove`](#0x2_vec_map_remove) -- [Function `pop`](#0x2_vec_map_pop) -- [Function `get_mut`](#0x2_vec_map_get_mut) -- [Function `get`](#0x2_vec_map_get) -- [Function `try_get`](#0x2_vec_map_try_get) -- [Function `contains`](#0x2_vec_map_contains) -- [Function `size`](#0x2_vec_map_size) -- [Function `is_empty`](#0x2_vec_map_is_empty) -- [Function `destroy_empty`](#0x2_vec_map_destroy_empty) -- [Function `into_keys_values`](#0x2_vec_map_into_keys_values) -- [Function `keys`](#0x2_vec_map_keys) -- [Function `get_idx_opt`](#0x2_vec_map_get_idx_opt) -- [Function `get_idx`](#0x2_vec_map_get_idx) -- [Function `get_entry_by_idx`](#0x2_vec_map_get_entry_by_idx) -- [Function `get_entry_by_idx_mut`](#0x2_vec_map_get_entry_by_idx_mut) -- [Function `remove_entry_by_idx`](#0x2_vec_map_remove_entry_by_idx) - - -

-use 0x1::option;
-use 0x1::vector;
-
- - - - - -## Struct `VecMap` - -A map data structure backed by a vector. The map is guaranteed not to contain duplicate keys, but entries -are *not* sorted by key--entries are included in insertion order. -All operations are O(N) in the size of the map--the intention of this data structure is only to provide -the convenience of programming against a map API. -Large maps should use handwritten parent/child relationships instead. -Maps that need sorted iteration rather than insertion order iteration should also be handwritten. - - -

-struct VecMap<K: copy, V> has copy, drop, store
-
- - - -
-Fields - - -
-
- -contents: vector<vec_map::Entry<K, V>> -
-
- -
-
- - -
- - - -## Struct `Entry` - -An entry in the map - - -

-struct Entry<K: copy, V> has copy, drop, store
-
- - - -
-Fields - - -
-
- -key: K -
-
- -
-
- -value: V -
-
- -
-
- - -
- - - -## Constants - - - - -This key already exists in the map - - -

-const EKeyAlreadyExists: u64 = 0;
-
- - - - - -This key does not exist in the map - - -

-const EKeyDoesNotExist: u64 = 1;
-
- - - - - -Trying to access an element of the map at an invalid index - - -

-const EIndexOutOfBounds: u64 = 3;
-
- - - - - -Trying to pop from a map that is empty - - -

-const EMapEmpty: u64 = 4;
-
- - - - - -Trying to destroy a map that is not empty - - -

-const EMapNotEmpty: u64 = 2;
-
- - - - - -## Function `empty` - -Create an empty -VecMap - - -

-public fun empty<K: copy, V>(): vec_map::VecMap<K, V>
-
- - - -
-Implementation - - -

-public fun empty<K: copy, V>(): VecMap<K,V> \{
-    VecMap \{ contents: vector[] }
-}
-
- - - -
- - - -## Function `insert` - -Insert the entry -key |-> -value into -self. -Aborts if -key is already bound in -self. - - -

-public fun insert<K: copy, V>(self: &mut vec_map::VecMap<K, V>, key: K, value: V)
-
- - - -
-Implementation - - -

-public fun insert<K: copy, V>(self: &mut VecMap<K,V>, key: K, value: V) \{
-    assert!(!self.contains(&key), EKeyAlreadyExists);
-    self.contents.push_back(Entry \{ key, value })
-}
-
- - - -
- - - -## Function `remove` - -Remove the entry -key |-> -value from self. Aborts if -key is not bound in -self. - - -

-public fun remove<K: copy, V>(self: &mut vec_map::VecMap<K, V>, key: &K): (K, V)
-
- - - -
-Implementation - - -

-public fun remove<K: copy, V>(self: &mut VecMap<K,V>, key: &K): (K, V) \{
-    let idx = self.get_idx(key);
-    let Entry \{ key, value } = self.contents.remove(idx);
-    (key, value)
-}
-
- - - -
- - - -## Function `pop` - -Pop the most recently inserted entry from the map. Aborts if the map is empty. - - -

-public fun pop<K: copy, V>(self: &mut vec_map::VecMap<K, V>): (K, V)
-
- - - -
-Implementation - - -

-public fun pop<K: copy, V>(self: &mut VecMap<K,V>): (K, V) \{
-    assert!(!self.contents.is_empty(), EMapEmpty);
-    let Entry \{ key, value } = self.contents.pop_back();
-    (key, value)
-}
-
- - - -
- - - -## Function `get_mut` - -Get a mutable reference to the value bound to -key in -self. -Aborts if -key is not bound in -self. - - -

-public fun get_mut<K: copy, V>(self: &mut vec_map::VecMap<K, V>, key: &K): &mut V
-
- - - -
-Implementation - - -

-public fun get_mut<K: copy, V>(self: &mut VecMap<K,V>, key: &K): &mut V \{
-    let idx = self.get_idx(key);
-    let entry = &mut self.contents[idx];
-    &mut entry.value
-}
-
- - - -
- - - -## Function `get` - -Get a reference to the value bound to -key in -self. -Aborts if -key is not bound in -self. - - -

-public fun get<K: copy, V>(self: &vec_map::VecMap<K, V>, key: &K): &V
-
- - - -
-Implementation - - -

-public fun get<K: copy, V>(self: &VecMap<K,V>, key: &K): &V \{
-    let idx = self.get_idx(key);
-    let entry = &self.contents[idx];
-    &entry.value
-}
-
- - - -
- - - -## Function `try_get` - -Safely try borrow a value bound to -key in -self. -Return Some(V) if the value exists, None otherwise. -Only works for a "copyable" value as references cannot be stored in -vector. - - -

-public fun try_get<K: copy, V: copy>(self: &vec_map::VecMap<K, V>, key: &K): option::Option<V>
-
- - - -
-Implementation - - -

-public fun try_get<K: copy, V: copy>(self: &VecMap<K,V>, key: &K): Option<V> \{
-    if (self.contains(key)) \{
-        option::some(*get(self, key))
-    } else \{
-        option::none()
-    }
-}
-
- - - -
- - - -## Function `contains` - -Return true if -self contains an entry for -key, false otherwise - - -

-public fun contains<K: copy, V>(self: &vec_map::VecMap<K, V>, key: &K): bool
-
- - - -
-Implementation - - -

-public fun contains<K: copy, V>(self: &VecMap<K, V>, key: &K): bool \{
-    get_idx_opt(self, key).is_some()
-}
-
- - - -
- - - -## Function `size` - -Return the number of entries in -self - - -

-public fun size<K: copy, V>(self: &vec_map::VecMap<K, V>): u64
-
- - - -
-Implementation - - -

-public fun size<K: copy, V>(self: &VecMap<K,V>): u64 \{
-    self.contents.length()
-}
-
- - - -
- - - -## Function `is_empty` - -Return true if -self has 0 elements, false otherwise - - -

-public fun is_empty<K: copy, V>(self: &vec_map::VecMap<K, V>): bool
-
- - - -
-Implementation - - -

-public fun is_empty<K: copy, V>(self: &VecMap<K,V>): bool \{
-    self.size() == 0
-}
-
- - - -
- - - -## Function `destroy_empty` - -Destroy an empty map. Aborts if -self is not empty - - -

-public fun destroy_empty<K: copy, V>(self: vec_map::VecMap<K, V>)
-
- - - -
-Implementation - - -

-public fun destroy_empty<K: copy, V>(self: VecMap<K, V>) \{
-    let VecMap \{ contents } = self;
-    assert!(contents.is_empty(), EMapNotEmpty);
-    contents.destroy_empty()
-}
-
- - - -
- - - -## Function `into_keys_values` - -Unpack -self into vectors of its keys and values. -The output keys and values are stored in insertion order, *not* sorted by key. - - -

-public fun into_keys_values<K: copy, V>(self: vec_map::VecMap<K, V>): (vector<K>, vector<V>)
-
- - - -
-Implementation - - -

-public fun into_keys_values<K: copy, V>(self: VecMap<K, V>): (vector<K>, vector<V>) \{
-    let VecMap \{ mut contents } = self;
-    // reverse the vector so the output keys and values will appear in insertion order
-    contents.reverse();
-    let mut i = 0;
-    let n = contents.length();
-    let mut keys = vector[];
-    let mut values = vector[];
-    while (i < n) \{
-        let Entry \{ key, value } = contents.pop_back();
-        keys.push_back(key);
-        values.push_back(value);
-        i = i + 1;
-    };
-    contents.destroy_empty();
-    (keys, values)
-}
-
- - - -
- - - -## Function `keys` - -Returns a list of keys in the map. -Do not assume any particular ordering. - - -

-public fun keys<K: copy, V>(self: &vec_map::VecMap<K, V>): vector<K>
-
- - - -
-Implementation - - -

-public fun keys<K: copy, V>(self: &VecMap<K, V>): vector<K> \{
-    let mut i = 0;
-    let n = self.contents.length();
-    let mut keys = vector[];
-    while (i < n) \{
-        let entry = self.contents.borrow(i);
-        keys.push_back(entry.key);
-        i = i + 1;
-    };
-    keys
-}
-
- - - -
- - - -## Function `get_idx_opt` - -Find the index of -key in -self. Return -None if -key is not in -self. -Note that map entries are stored in insertion order, *not* sorted by key. - - -

-public fun get_idx_opt<K: copy, V>(self: &vec_map::VecMap<K, V>, key: &K): option::Option<u64>
-
- - - -
-Implementation - - -

-public fun get_idx_opt<K: copy, V>(self: &VecMap<K,V>, key: &K): Option<u64> \{
-    let mut i = 0;
-    let n = size(self);
-    while (i < n) \{
-        if (&self.contents[i].key == key) \{
-            return option::some(i)
-        };
-        i = i + 1;
-    };
-    option::none()
-}
-
- - - -
- - - -## Function `get_idx` - -Find the index of -key in -self. Aborts if -key is not in -self. -Note that map entries are stored in insertion order, *not* sorted by key. - - -

-public fun get_idx<K: copy, V>(self: &vec_map::VecMap<K, V>, key: &K): u64
-
- - - -
-Implementation - - -

-public fun get_idx<K: copy, V>(self: &VecMap<K,V>, key: &K): u64 \{
-    let idx_opt = self.get_idx_opt(key);
-    assert!(idx_opt.is_some(), EKeyDoesNotExist);
-    idx_opt.destroy_some()
-}
-
- - - -
- - - -## Function `get_entry_by_idx` - -Return a reference to the -idxth entry of -self. This gives direct access into the backing array of the map--use with caution. -Note that map entries are stored in insertion order, *not* sorted by key. -Aborts if -idx is greater than or equal to -size(self) - - -

-public fun get_entry_by_idx<K: copy, V>(self: &vec_map::VecMap<K, V>, idx: u64): (&K, &V)
-
- - - -
-Implementation - - -

-public fun get_entry_by_idx<K: copy, V>(self: &VecMap<K, V>, idx: u64): (&K, &V) \{
-    assert!(idx < size(self), EIndexOutOfBounds);
-    let entry = &self.contents[idx];
-    (&entry.key, &entry.value)
-}
-
- - - -
- - - -## Function `get_entry_by_idx_mut` - -Return a mutable reference to the -idxth entry of -self. This gives direct access into the backing array of the map--use with caution. -Note that map entries are stored in insertion order, *not* sorted by key. -Aborts if -idx is greater than or equal to -size(self) - - -

-public fun get_entry_by_idx_mut<K: copy, V>(self: &mut vec_map::VecMap<K, V>, idx: u64): (&K, &mut V)
-
- - - -
-Implementation - - -

-public fun get_entry_by_idx_mut<K: copy, V>(self: &mut VecMap<K, V>, idx: u64): (&K, &mut V) \{
-    assert!(idx < size(self), EIndexOutOfBounds);
-    let entry = &mut self.contents[idx];
-    (&entry.key, &mut entry.value)
-}
-
- - - -
- - - -## Function `remove_entry_by_idx` - -Remove the entry at index -idx from self. -Aborts if -idx is greater than or equal to -size(self) - - -

-public fun remove_entry_by_idx<K: copy, V>(self: &mut vec_map::VecMap<K, V>, idx: u64): (K, V)
-
- - - -
-Implementation - - -

-public fun remove_entry_by_idx<K: copy, V>(self: &mut VecMap<K, V>, idx: u64): (K, V) \{
-    assert!(idx < size(self), EIndexOutOfBounds);
-    let Entry \{ key, value } = self.contents.remove(idx);
-    (key, value)
-}
-
- - - -
diff --git a/crates/iota-framework/docs/iota-framework/vec_set.mdx b/crates/iota-framework/docs/iota-framework/vec_set.mdx deleted file mode 100644 index c7e7999aa5c..00000000000 --- a/crates/iota-framework/docs/iota-framework/vec_set.mdx +++ /dev/null @@ -1,430 +0,0 @@ ---- -title: Module `0x2::vec_set` ---- -import Link from '@docusaurus/Link'; - - - - -- [Struct `VecSet`](#0x2_vec_set_VecSet) -- [Constants](#@Constants_0) -- [Function `empty`](#0x2_vec_set_empty) -- [Function `singleton`](#0x2_vec_set_singleton) -- [Function `insert`](#0x2_vec_set_insert) -- [Function `remove`](#0x2_vec_set_remove) -- [Function `contains`](#0x2_vec_set_contains) -- [Function `size`](#0x2_vec_set_size) -- [Function `is_empty`](#0x2_vec_set_is_empty) -- [Function `into_keys`](#0x2_vec_set_into_keys) -- [Function `keys`](#0x2_vec_set_keys) -- [Function `get_idx_opt`](#0x2_vec_set_get_idx_opt) -- [Function `get_idx`](#0x2_vec_set_get_idx) - - -

-use 0x1::option;
-use 0x1::vector;
-
- - - - - -## Struct `VecSet` - -A set data structure backed by a vector. The set is guaranteed not to -contain duplicate keys. All operations are O(N) in the size of the set -- the intention of this data structure is only to provide the convenience -of programming against a set API. Sets that need sorted iteration rather -than insertion order iteration should be handwritten. - - -

-struct VecSet<K: copy, drop> has copy, drop, store
-
- - - -
-Fields - - -
-
- -contents: vector<K> -
-
- -
-
- - -
- - - -## Constants - - - - -This key already exists in the map - - -

-const EKeyAlreadyExists: u64 = 0;
-
- - - - - -This key does not exist in the map - - -

-const EKeyDoesNotExist: u64 = 1;
-
- - - - - -## Function `empty` - -Create an empty -VecSet - - -

-public fun empty<K: copy, drop>(): vec_set::VecSet<K>
-
- - - -
-Implementation - - -

-public fun empty<K: copy + drop>(): VecSet<K> \{
-    VecSet \{ contents: vector[] }
-}
-
- - - -
- - - -## Function `singleton` - -Create a singleton -VecSet that only contains one element. - - -

-public fun singleton<K: copy, drop>(key: K): vec_set::VecSet<K>
-
- - - -
-Implementation - - -

-public fun singleton<K: copy + drop>(key: K): VecSet<K> \{
-    VecSet \{ contents: vector[key] }
-}
-
- - - -
- - - -## Function `insert` - -Insert a -key into self. -Aborts if -key is already present in -self. - - -

-public fun insert<K: copy, drop>(self: &mut vec_set::VecSet<K>, key: K)
-
- - - -
-Implementation - - -

-public fun insert<K: copy + drop>(self: &mut VecSet<K>, key: K) \{
-    assert!(!self.contains(&key), EKeyAlreadyExists);
-    self.contents.push_back(key)
-}
-
- - - -
- - - -## Function `remove` - -Remove the entry -key from self. Aborts if -key is not present in -self. - - -

-public fun remove<K: copy, drop>(self: &mut vec_set::VecSet<K>, key: &K)
-
- - - -
-Implementation - - -

-public fun remove<K: copy + drop>(self: &mut VecSet<K>, key: &K) \{
-    let idx = get_idx(self, key);
-    self.contents.remove(idx);
-}
-
- - - -
- - - -## Function `contains` - -Return true if -self contains an entry for -key, false otherwise - - -

-public fun contains<K: copy, drop>(self: &vec_set::VecSet<K>, key: &K): bool
-
- - - -
-Implementation - - -

-public fun contains<K: copy + drop>(self: &VecSet<K>, key: &K): bool \{
-    get_idx_opt(self, key).is_some()
-}
-
- - - -
- - - -## Function `size` - -Return the number of entries in -self - - -

-public fun size<K: copy, drop>(self: &vec_set::VecSet<K>): u64
-
- - - -
-Implementation - - -

-public fun size<K: copy + drop>(self: &VecSet<K>): u64 \{
-    self.contents.length()
-}
-
- - - -
- - - -## Function `is_empty` - -Return true if -self has 0 elements, false otherwise - - -

-public fun is_empty<K: copy, drop>(self: &vec_set::VecSet<K>): bool
-
- - - -
-Implementation - - -

-public fun is_empty<K: copy + drop>(self: &VecSet<K>): bool \{
-    size(self) == 0
-}
-
- - - -
- - - -## Function `into_keys` - -Unpack -self into vectors of keys. -The output keys are stored in insertion order, *not* sorted. - - -

-public fun into_keys<K: copy, drop>(self: vec_set::VecSet<K>): vector<K>
-
- - - -
-Implementation - - -

-public fun into_keys<K: copy + drop>(self: VecSet<K>): vector<K> \{
-    let VecSet \{ contents } = self;
-    contents
-}
-
- - - -
- - - -## Function `keys` - -Borrow the -contents of the -VecSet to access content by index -without unpacking. The contents are stored in insertion order, -*not* sorted. - - -

-public fun keys<K: copy, drop>(self: &vec_set::VecSet<K>): &vector<K>
-
- - - -
-Implementation - - -

-public fun keys<K: copy + drop>(self: &VecSet<K>): &vector<K> \{
-    &self.contents
-}
-
- - - -
- - - -## Function `get_idx_opt` - -Find the index of -key in -self. Return -None if -key is not in -self. -Note that keys are stored in insertion order, *not* sorted. - - -

-fun get_idx_opt<K: copy, drop>(self: &vec_set::VecSet<K>, key: &K): option::Option<u64>
-
- - - -
-Implementation - - -

-fun get_idx_opt<K: copy + drop>(self: &VecSet<K>, key: &K): Option<u64> \{
-    let mut i = 0;
-    let n = size(self);
-    while (i < n) \{
-        if (&self.contents[i] == key) \{
-            return option::some(i)
-        };
-        i = i + 1;
-    };
-    option::none()
-}
-
- - - -
- - - -## Function `get_idx` - -Find the index of -key in -self. Aborts if -key is not in -self. -Note that map entries are stored in insertion order, *not* sorted. - - -

-fun get_idx<K: copy, drop>(self: &vec_set::VecSet<K>, key: &K): u64
-
- - - -
-Implementation - - -

-fun get_idx<K: copy + drop>(self: &VecSet<K>, key: &K): u64 \{
-    let idx_opt = get_idx_opt(self, key);
-    assert!(idx_opt.is_some(), EKeyDoesNotExist);
-    idx_opt.destroy_some()
-}
-
- - - -
diff --git a/crates/iota-framework/docs/iota-framework/versioned.mdx b/crates/iota-framework/docs/iota-framework/versioned.mdx deleted file mode 100644 index 94974b9b2f0..00000000000 --- a/crates/iota-framework/docs/iota-framework/versioned.mdx +++ /dev/null @@ -1,334 +0,0 @@ ---- -title: Module `0x2::versioned` ---- -import Link from '@docusaurus/Link'; - - - - -- [Resource `Versioned`](#0x2_versioned_Versioned) -- [Struct `VersionChangeCap`](#0x2_versioned_VersionChangeCap) -- [Constants](#@Constants_0) -- [Function `create`](#0x2_versioned_create) -- [Function `version`](#0x2_versioned_version) -- [Function `load_value`](#0x2_versioned_load_value) -- [Function `load_value_mut`](#0x2_versioned_load_value_mut) -- [Function `remove_value_for_upgrade`](#0x2_versioned_remove_value_for_upgrade) -- [Function `upgrade`](#0x2_versioned_upgrade) -- [Function `destroy`](#0x2_versioned_destroy) - - -

-use 0x2::dynamic_field;
-use 0x2::object;
-use 0x2::tx_context;
-
- - - - - -## Resource `Versioned` - -A wrapper type that supports versioning of the inner type. -The inner type is a dynamic field of the Versioned object, and is keyed using version. -User of this type could load the inner object using corresponding type based on the version. -You can also upgrade the inner object to a new type version. -If you want to support lazy upgrade of the inner type, one caveat is that all APIs would have -to use mutable reference even if it's a read-only API. - - -

-struct Versioned has store, key
-
- - - -
-Fields - - -
-
- -id: object::UID -
-
- -
-
- -version: u64 -
-
- -
-
- - -
- - - -## Struct `VersionChangeCap` - -Represents a hot potato object generated when we take out the dynamic field. -This is to make sure that we always put a new value back. - - -

-struct VersionChangeCap
-
- - - -
-Fields - - -
-
- -versioned_id: object::ID -
-
- -
-
- -old_version: u64 -
-
- -
-
- - -
- - - -## Constants - - - - -Failed to upgrade the inner object due to invalid capability or new version. - - -

-const EInvalidUpgrade: u64 = 0;
-
- - - - - -## Function `create` - -Create a new Versioned object that contains a initial value of type -T with an initial version. - - -

-public fun create<T: store>(init_version: u64, init_value: T, ctx: &mut tx_context::TxContext): versioned::Versioned
-
- - - -
-Implementation - - -

-public fun create<T: store>(init_version: u64, init_value: T, ctx: &mut TxContext): Versioned \{
-    let mut self = Versioned \{
-        id: object::new(ctx),
-        version: init_version,
-    };
-    dynamic_field::add(&mut self.id, init_version, init_value);
-    self
-}
-
- - - -
- - - -## Function `version` - -Get the current version of the inner type. - - -

-public fun version(self: &versioned::Versioned): u64
-
- - - -
-Implementation - - -

-public fun version(self: &Versioned): u64 \{
-    self.version
-}
-
- - - -
- - - -## Function `load_value` - -Load the inner value based on the current version. Caller specifies an expected type T. -If the type mismatch, the load will fail. - - -

-public fun load_value<T: store>(self: &versioned::Versioned): &T
-
- - - -
-Implementation - - -

-public fun load_value<T: store>(self: &Versioned): &T \{
-    dynamic_field::borrow(&self.id, self.version)
-}
-
- - - -
- - - -## Function `load_value_mut` - -Similar to load_value, but return a mutable reference. - - -

-public fun load_value_mut<T: store>(self: &mut versioned::Versioned): &mut T
-
- - - -
-Implementation - - -

-public fun load_value_mut<T: store>(self: &mut Versioned): &mut T \{
-    dynamic_field::borrow_mut(&mut self.id, self.version)
-}
-
- - - -
- - - -## Function `remove_value_for_upgrade` - -Take the inner object out for upgrade. To ensure we always upgrade properly, a capability object is returned -and must be used when we upgrade. - - -

-public fun remove_value_for_upgrade<T: store>(self: &mut versioned::Versioned): (T, versioned::VersionChangeCap)
-
- - - -
-Implementation - - -

-public fun remove_value_for_upgrade<T: store>(self: &mut Versioned): (T, VersionChangeCap) \{
-    (
-        dynamic_field::remove(&mut self.id, self.version),
-        VersionChangeCap \{
-            versioned_id: object::id(self),
-            old_version: self.version,
-        }
-    )
-}
-
- - - -
- - - -## Function `upgrade` - -Upgrade the inner object with a new version and new value. Must use the capability returned -by calling remove_value_for_upgrade. - - -

-public fun upgrade<T: store>(self: &mut versioned::Versioned, new_version: u64, new_value: T, cap: versioned::VersionChangeCap)
-
- - - -
-Implementation - - -

-public fun upgrade<T: store>(self: &mut Versioned, new_version: u64, new_value: T, cap: VersionChangeCap) \{
-    let VersionChangeCap \{ versioned_id, old_version } = cap;
-    assert!(versioned_id == object::id(self), EInvalidUpgrade);
-    assert!(old_version < new_version, EInvalidUpgrade);
-    dynamic_field::add(&mut self.id, new_version, new_value);
-    self.version = new_version;
-}
-
- - - -
- - - -## Function `destroy` - -Destroy this Versioned container, and return the inner object. - - -

-public fun destroy<T: store>(self: versioned::Versioned): T
-
- - - -
-Implementation - - -

-public fun destroy<T: store>(self: Versioned): T \{
-    let Versioned \{ mut id, version } = self;
-    let ret = dynamic_field::remove(&mut id, version);
-    id.delete();
-    ret
-}
-
- - - -
diff --git a/crates/iota-framework/docs/iota-framework/zklogin_verified_id.mdx b/crates/iota-framework/docs/iota-framework/zklogin_verified_id.mdx deleted file mode 100644 index 595514ee4c8..00000000000 --- a/crates/iota-framework/docs/iota-framework/zklogin_verified_id.mdx +++ /dev/null @@ -1,385 +0,0 @@ ---- -title: Module `0x2::zklogin_verified_id` ---- -import Link from '@docusaurus/Link'; - - - - -- [Resource `VerifiedID`](#0x2_zklogin_verified_id_VerifiedID) -- [Constants](#@Constants_0) -- [Function `owner`](#0x2_zklogin_verified_id_owner) -- [Function `key_claim_name`](#0x2_zklogin_verified_id_key_claim_name) -- [Function `key_claim_value`](#0x2_zklogin_verified_id_key_claim_value) -- [Function `issuer`](#0x2_zklogin_verified_id_issuer) -- [Function `audience`](#0x2_zklogin_verified_id_audience) -- [Function `delete`](#0x2_zklogin_verified_id_delete) -- [Function `verify_zklogin_id`](#0x2_zklogin_verified_id_verify_zklogin_id) -- [Function `check_zklogin_id`](#0x2_zklogin_verified_id_check_zklogin_id) -- [Function `check_zklogin_id_internal`](#0x2_zklogin_verified_id_check_zklogin_id_internal) - - -

-use 0x1::string;
-use 0x2::object;
-use 0x2::tx_context;
-
- - - - - -## Resource `VerifiedID` - -Posession of a VerifiedID proves that the user's address was created using zklogin and the given parameters. - - -

-struct VerifiedID has key
-
- - - -
-Fields - - -
-
- -id: object::UID -
-
- The ID of this VerifiedID -
-
- -owner: address -
-
- The address this VerifiedID is associated with -
-
- -key_claim_name: string::String -
-
- The name of the key claim -
-
- -key_claim_value: string::String -
-
- The value of the key claim -
-
- -issuer: string::String -
-
- The issuer -
-
- -audience: string::String -
-
- The audience (wallet) -
-
- - -
- - - -## Constants - - - - - - -

-const EFunctionDisabled: u64 = 0;
-
- - - - - -## Function `owner` - -Returns the address associated with the given VerifiedID - - -

-public fun owner(verified_id: &zklogin_verified_id::VerifiedID): address
-
- - - -
-Implementation - - -

-public fun owner(verified_id: &VerifiedID): address \{
-    verified_id.owner
-}
-
- - - -
- - - -## Function `key_claim_name` - -Returns the name of the key claim associated with the given VerifiedID - - -

-public fun key_claim_name(verified_id: &zklogin_verified_id::VerifiedID): &string::String
-
- - - -
-Implementation - - -

-public fun key_claim_name(verified_id: &VerifiedID): &String \{
-    &verified_id.key_claim_name
-}
-
- - - -
- - - -## Function `key_claim_value` - -Returns the value of the key claim associated with the given VerifiedID - - -

-public fun key_claim_value(verified_id: &zklogin_verified_id::VerifiedID): &string::String
-
- - - -
-Implementation - - -

-public fun key_claim_value(verified_id: &VerifiedID): &String \{
-    &verified_id.key_claim_value
-}
-
- - - -
- - - -## Function `issuer` - -Returns the issuer associated with the given VerifiedID - - -

-public fun issuer(verified_id: &zklogin_verified_id::VerifiedID): &string::String
-
- - - -
-Implementation - - -

-public fun issuer(verified_id: &VerifiedID): &String \{
-    &verified_id.issuer
-}
-
- - - -
- - - -## Function `audience` - -Returns the audience (wallet) associated with the given VerifiedID - - -

-public fun audience(verified_id: &zklogin_verified_id::VerifiedID): &string::String
-
- - - -
-Implementation - - -

-public fun audience(verified_id: &VerifiedID): &String \{
-    &verified_id.audience
-}
-
- - - -
- - - -## Function `delete` - -Delete a VerifiedID - - -

-public fun delete(verified_id: zklogin_verified_id::VerifiedID)
-
- - - -
-Implementation - - -

-public fun delete(verified_id: VerifiedID) \{
-    let VerifiedID \{ id, owner: _, key_claim_name: _, key_claim_value: _, issuer: _, audience: _ } = verified_id;
-    id.delete();
-}
-
- - - -
- - - -## Function `verify_zklogin_id` - -This function has been disabled. - - -

-public fun verify_zklogin_id(_key_claim_name: string::String, _key_claim_value: string::String, _issuer: string::String, _audience: string::String, _pin_hash: u256, _ctx: &mut tx_context::TxContext)
-
- - - -
-Implementation - - -

-public fun verify_zklogin_id(
-    _key_claim_name: String,
-    _key_claim_value: String,
-    _issuer: String,
-    _audience: String,
-    _pin_hash: u256,
-    _ctx: &mut TxContext,
-) \{
-    assert!(false, EFunctionDisabled);
-}
-
- - - -
- - - -## Function `check_zklogin_id` - -This function has been disabled. - - -

-public fun check_zklogin_id(_address: address, _key_claim_name: &string::String, _key_claim_value: &string::String, _issuer: &string::String, _audience: &string::String, _pin_hash: u256): bool
-
- - - -
-Implementation - - -

-public fun check_zklogin_id(
-    _address: address,
-    _key_claim_name: &String,
-    _key_claim_value: &String,
-    _issuer: &String,
-    _audience: &String,
-    _pin_hash: u256
-): bool \{
-    assert!(false, EFunctionDisabled);
-    false
-}
-
- - - -
- - - -## Function `check_zklogin_id_internal` - -Returns true if -address was created using zklogin and the given parameters. - -Aborts with -EInvalidInput if any of -kc_name, -kc_value, -iss and -aud is not a properly encoded UTF-8 -string or if the inputs are longer than the allowed upper bounds: -kc_name must be at most 32 characters, - -kc_value must be at most 115 characters and -aud must be at most 145 characters. - - -

-fun check_zklogin_id_internal(address: address, key_claim_name: &vector<u8>, key_claim_value: &vector<u8>, issuer: &vector<u8>, audience: &vector<u8>, pin_hash: u256): bool
-
- - - -
-Implementation - - -

-native fun check_zklogin_id_internal(
-    address: address,
-    key_claim_name: &vector<u8>,
-    key_claim_value: &vector<u8>,
-    issuer: &vector<u8>,
-    audience: &vector<u8>,
-    pin_hash: u256
-): bool;
-
- - - -
diff --git a/crates/iota-framework/docs/iota-framework/zklogin_verified_issuer.mdx b/crates/iota-framework/docs/iota-framework/zklogin_verified_issuer.mdx deleted file mode 100644 index 41ffd82c959..00000000000 --- a/crates/iota-framework/docs/iota-framework/zklogin_verified_issuer.mdx +++ /dev/null @@ -1,290 +0,0 @@ ---- -title: Module `0x2::zklogin_verified_issuer` ---- -import Link from '@docusaurus/Link'; - - - - -- [Resource `VerifiedIssuer`](#0x2_zklogin_verified_issuer_VerifiedIssuer) -- [Constants](#@Constants_0) -- [Function `owner`](#0x2_zklogin_verified_issuer_owner) -- [Function `issuer`](#0x2_zklogin_verified_issuer_issuer) -- [Function `delete`](#0x2_zklogin_verified_issuer_delete) -- [Function `verify_zklogin_issuer`](#0x2_zklogin_verified_issuer_verify_zklogin_issuer) -- [Function `check_zklogin_issuer`](#0x2_zklogin_verified_issuer_check_zklogin_issuer) -- [Function `check_zklogin_issuer_internal`](#0x2_zklogin_verified_issuer_check_zklogin_issuer_internal) - - -

-use 0x1::string;
-use 0x2::object;
-use 0x2::transfer;
-use 0x2::tx_context;
-
- - - - - -## Resource `VerifiedIssuer` - -Posession of a VerifiedIssuer proves that the user's address was created using zklogin and with the given issuer -(identity provider). - - -

-struct VerifiedIssuer has key
-
- - - -
-Fields - - -
-
- -id: object::UID -
-
- The ID of this VerifiedIssuer -
-
- -owner: address -
-
- The address this VerifiedID is associated with -
-
- -issuer: string::String -
-
- The issuer -
-
- - -
- - - -## Constants - - - - -Error if the proof consisting of the inputs provided to the verification function is invalid. - - -

-const EInvalidInput: u64 = 0;
-
- - - - - -Error if the proof consisting of the inputs provided to the verification function is invalid. - - -

-const EInvalidProof: u64 = 1;
-
- - - - - -## Function `owner` - -Returns the address associated with the given VerifiedIssuer - - -

-public fun owner(verified_issuer: &zklogin_verified_issuer::VerifiedIssuer): address
-
- - - -
-Implementation - - -

-public fun owner(verified_issuer: &VerifiedIssuer): address \{
-    verified_issuer.owner
-}
-
- - - -
- - - -## Function `issuer` - -Returns the issuer associated with the given VerifiedIssuer - - -

-public fun issuer(verified_issuer: &zklogin_verified_issuer::VerifiedIssuer): &string::String
-
- - - -
-Implementation - - -

-public fun issuer(verified_issuer: &VerifiedIssuer): &String \{
-    &verified_issuer.issuer
-}
-
- - - -
- - - -## Function `delete` - -Delete a VerifiedIssuer - - -

-public fun delete(verified_issuer: zklogin_verified_issuer::VerifiedIssuer)
-
- - - -
-Implementation - - -

-public fun delete(verified_issuer: VerifiedIssuer) \{
-    let VerifiedIssuer \{ id, owner: _, issuer: _ } = verified_issuer;
-    id.delete();
-}
-
- - - -
- - - -## Function `verify_zklogin_issuer` - -Verify that the caller's address was created using zklogin with the given issuer. If so, a VerifiedIssuer object -with the issuers id transfered to the caller. - -Aborts with -EInvalidProof if the verification fails. - - -

-public fun verify_zklogin_issuer(address_seed: u256, issuer: string::String, ctx: &mut tx_context::TxContext)
-
- - - -
-Implementation - - -

-public fun verify_zklogin_issuer(
-    address_seed: u256,
-    issuer: String,
-    ctx: &mut TxContext,
-) \{
-    let sender = ctx.sender();
-    assert!(check_zklogin_issuer(sender, address_seed, &issuer), EInvalidProof);
-    transfer::transfer(
-        VerifiedIssuer \{
-            id: object::new(ctx),
-            owner: sender,
-            issuer
-        },
-        sender
-    )
-}
-
- - - -
- - - -## Function `check_zklogin_issuer` - -Returns true if -address was created using zklogin with the given issuer and address seed. - - -

-public fun check_zklogin_issuer(address: address, address_seed: u256, issuer: &string::String): bool
-
- - - -
-Implementation - - -

-public fun check_zklogin_issuer(
-    address: address,
-    address_seed: u256,
-    issuer: &String,
-): bool \{
-    check_zklogin_issuer_internal(address, address_seed, issuer.bytes())
-}
-
- - - -
- - - -## Function `check_zklogin_issuer_internal` - -Returns true if -address was created using zklogin with the given issuer and address seed. - -Aborts with -EInvalidInput if the -iss input is not a valid UTF-8 string. - - -

-fun check_zklogin_issuer_internal(address: address, address_seed: u256, issuer: &vector<u8>): bool
-
- - - -
-Implementation - - -

-native fun check_zklogin_issuer_internal(
-    address: address,
-    address_seed: u256,
-    issuer: &vector<u8>,
-): bool;
-
- - - -
diff --git a/crates/iota-framework/docs/iota-system/genesis.mdx b/crates/iota-framework/docs/iota-system/genesis.mdx deleted file mode 100644 index 85eb8b6a3b3..00000000000 --- a/crates/iota-framework/docs/iota-system/genesis.mdx +++ /dev/null @@ -1,614 +0,0 @@ ---- -title: Module `0x3::genesis` ---- -import Link from '@docusaurus/Link'; - - - - -- [Struct `GenesisValidatorMetadata`](#0x3_genesis_GenesisValidatorMetadata) -- [Struct `GenesisChainParameters`](#0x3_genesis_GenesisChainParameters) -- [Struct `TokenDistributionSchedule`](#0x3_genesis_TokenDistributionSchedule) -- [Struct `TokenAllocation`](#0x3_genesis_TokenAllocation) -- [Constants](#@Constants_0) -- [Function `create`](#0x3_genesis_create) -- [Function `allocate_tokens`](#0x3_genesis_allocate_tokens) -- [Function `activate_validators`](#0x3_genesis_activate_validators) - - -

-use 0x1::option;
-use 0x1::string;
-use 0x1::vector;
-use 0x2::balance;
-use 0x2::coin;
-use 0x2::iota;
-use 0x2::object;
-use 0x2::timelock;
-use 0x2::tx_context;
-use 0x3::iota_system;
-use 0x3::iota_system_state_inner;
-use 0x3::timelocked_staking;
-use 0x3::validator;
-use 0x3::validator_set;
-
- - - - - -## Struct `GenesisValidatorMetadata` - - - -

-struct GenesisValidatorMetadata has copy, drop
-
- - - -
-Fields - - -
-
- -name: vector<u8> -
-
- -
-
- -description: vector<u8> -
-
- -
-
- -image_url: vector<u8> -
-
- -
-
- -project_url: vector<u8> -
-
- -
-
- -iota_address: address -
-
- -
-
- -gas_price: u64 -
-
- -
-
- -commission_rate: u64 -
-
- -
-
- -protocol_public_key: vector<u8> -
-
- -
-
- -proof_of_possession: vector<u8> -
-
- -
-
- -network_public_key: vector<u8> -
-
- -
-
- -worker_public_key: vector<u8> -
-
- -
-
- -network_address: vector<u8> -
-
- -
-
- -p2p_address: vector<u8> -
-
- -
-
- -primary_address: vector<u8> -
-
- -
-
- -worker_address: vector<u8> -
-
- -
-
- - -
- - - -## Struct `GenesisChainParameters` - - - -

-struct GenesisChainParameters has copy, drop
-
- - - -
-Fields - - -
-
- -protocol_version: u64 -
-
- -
-
- -chain_start_timestamp_ms: u64 -
-
- -
-
- -epoch_duration_ms: u64 -
-
- -
-
- -max_validator_count: u64 -
-
- -
-
- -min_validator_joining_stake: u64 -
-
- -
-
- -validator_low_stake_threshold: u64 -
-
- -
-
- -validator_very_low_stake_threshold: u64 -
-
- -
-
- -validator_low_stake_grace_period: u64 -
-
- -
-
- - -
- - - -## Struct `TokenDistributionSchedule` - - - -

-struct TokenDistributionSchedule
-
- - - -
-Fields - - -
-
- -pre_minted_supply: u64 -
-
- -
-
- -allocations: vector<genesis::TokenAllocation> -
-
- -
-
- - -
- - - -## Struct `TokenAllocation` - - - -

-struct TokenAllocation
-
- - - -
-Fields - - -
-
- -recipient_address: address -
-
- -
-
- -amount_nanos: u64 -
-
- -
-
- -staked_with_validator: option::Option<address> -
-
- Indicates if this allocation should be staked at genesis and with which validator -
-
- -staked_with_timelock_expiration: option::Option<u64> -
-
- Indicates if this allocation should be staked with timelock at genesis - and contains its timelock_expiration -
-
- - -
- - - -## Constants - - - - -The -create function was called at a non-genesis epoch. - - -

-const ENotCalledAtGenesis: u64 = 0;
-
- - - - - -The -create function was called with duplicate validators. - - -

-const EDuplicateValidator: u64 = 1;
-
- - - - - -The -create function was called with wrong pre-minted supply. - - -

-const EWrongPreMintedSupply: u64 = 2;
-
- - - - - -## Function `create` - -This function will be explicitly called once at genesis. -It will create a singleton IotaSystemState object, which contains -all the information we need in the system. - - -

-fun create(iota_system_state_id: object::UID, iota_treasury_cap: iota::IotaTreasuryCap, genesis_chain_parameters: genesis::GenesisChainParameters, genesis_validators: vector<genesis::GenesisValidatorMetadata>, token_distribution_schedule: genesis::TokenDistributionSchedule, timelock_genesis_label: option::Option<string::String>, system_timelock_cap: timelock::SystemTimelockCap, ctx: &mut tx_context::TxContext)
-
- - - -
-Implementation - - -

-fun create(
-    iota_system_state_id: UID,
-    mut iota_treasury_cap: IotaTreasuryCap,
-    genesis_chain_parameters: GenesisChainParameters,
-    genesis_validators: vector<GenesisValidatorMetadata>,
-    token_distribution_schedule: TokenDistributionSchedule,
-    timelock_genesis_label: Option<String>,
-    system_timelock_cap: SystemTimelockCap,
-    ctx: &mut TxContext,
-) \{
-    // Ensure this is only called at genesis
-    assert!(ctx.epoch() == 0, ENotCalledAtGenesis);
-
-    let TokenDistributionSchedule \{
-        pre_minted_supply,
-        allocations,
-    } = token_distribution_schedule;
-
-    assert!(iota_treasury_cap.total_supply() == pre_minted_supply, EWrongPreMintedSupply);
-
-    let storage_fund = balance::zero();
-
-    // Create all the `Validator` structs
-    let mut validators = vector[];
-    let count = genesis_validators.length();
-    let mut i = 0;
-    while (i < count) \{
-        let GenesisValidatorMetadata \{
-            name,
-            description,
-            image_url,
-            project_url,
-            iota_address,
-            gas_price,
-            commission_rate,
-            protocol_public_key,
-            proof_of_possession,
-            network_public_key,
-            worker_public_key,
-            network_address,
-            p2p_address,
-            primary_address,
-            worker_address,
-        } = genesis_validators[i];
-
-        let validator = validator::new(
-            iota_address,
-            protocol_public_key,
-            network_public_key,
-            worker_public_key,
-            proof_of_possession,
-            name,
-            description,
-            image_url,
-            project_url,
-            network_address,
-            p2p_address,
-            primary_address,
-            worker_address,
-            gas_price,
-            commission_rate,
-            ctx
-        );
-
-        // Ensure that each validator is unique
-        assert!(
-            !validator_set::is_duplicate_validator(&validators, &validator),
-            EDuplicateValidator,
-        );
-
-        validators.push_back(validator);
-
-        i = i + 1;
-    };
-
-    // Allocate tokens and staking operations
-    allocate_tokens(
-        &mut iota_treasury_cap,
-        allocations,
-        &mut validators,
-        timelock_genesis_label,
-        ctx
-    );
-
-    // Activate all validators
-    activate_validators(&mut validators);
-
-    let system_parameters = iota_system_state_inner::create_system_parameters(
-        genesis_chain_parameters.epoch_duration_ms,
-
-        // Validator committee parameters
-        genesis_chain_parameters.max_validator_count,
-        genesis_chain_parameters.min_validator_joining_stake,
-        genesis_chain_parameters.validator_low_stake_threshold,
-        genesis_chain_parameters.validator_very_low_stake_threshold,
-        genesis_chain_parameters.validator_low_stake_grace_period,
-
-        ctx,
-    );
-
-    iota_system::create(
-        iota_system_state_id,
-        iota_treasury_cap,
-        validators,
-        storage_fund,
-        genesis_chain_parameters.protocol_version,
-        genesis_chain_parameters.chain_start_timestamp_ms,
-        system_parameters,
-        system_timelock_cap,
-        ctx,
-    );
-}
-
- - - -
- - - -## Function `allocate_tokens` - - - -

-fun allocate_tokens(iota_treasury_cap: &mut iota::IotaTreasuryCap, allocations: vector<genesis::TokenAllocation>, validators: &mut vector<validator::Validator>, timelock_genesis_label: option::Option<string::String>, ctx: &mut tx_context::TxContext)
-
- - - -
-Implementation - - -

-fun allocate_tokens(
-    iota_treasury_cap: &mut IotaTreasuryCap,
-    mut allocations: vector<TokenAllocation>,
-    validators: &mut vector<Validator>,
-    timelock_genesis_label: Option<String>,
-    ctx: &mut TxContext,
-) \{
-
-    while (!allocations.is_empty()) \{
-        let TokenAllocation \{
-            recipient_address,
-            amount_nanos,
-            staked_with_validator,
-            staked_with_timelock_expiration,
-        } = allocations.pop_back();
-
-        let allocation_balance = iota_treasury_cap.mint_balance(amount_nanos, ctx);
-
-        if (staked_with_validator.is_some()) \{
-            let validator_address = staked_with_validator.destroy_some();
-            let validator = validator_set::get_validator_mut(
-                validators, validator_address
-            );
-            if (staked_with_timelock_expiration.is_some()) \{
-                let timelock_expiration = staked_with_timelock_expiration.destroy_some();
-                timelocked_staking::request_add_stake_at_genesis(
-                    validator,
-                    allocation_balance,
-                    recipient_address,
-                    timelock_expiration,
-                    timelock_genesis_label,
-                    ctx
-                );
-            } else \{
-                validator.request_add_stake_at_genesis(
-                    allocation_balance,
-                    recipient_address,
-                    ctx
-                );
-            }
-        } else \{
-            iota::transfer(
-                allocation_balance.into_coin(ctx),
-                recipient_address,
-            );
-        };
-    };
-    allocations.destroy_empty();
-}
-
- - - -
- - - -## Function `activate_validators` - - - -

-fun activate_validators(validators: &mut vector<validator::Validator>)
-
- - - -
-Implementation - - -

-fun activate_validators(validators: &mut vector<Validator>) \{
-    // Activate all genesis validators
-    let count = validators.length();
-    let mut i = 0;
-    while (i < count) \{
-        let validator = &mut validators[i];
-        validator.activate(0);
-
-        i = i + 1;
-    };
-
-}
-
- - - -
diff --git a/crates/iota-framework/docs/iota-system/iota_system.mdx b/crates/iota-framework/docs/iota-system/iota_system.mdx deleted file mode 100644 index b9366862741..00000000000 --- a/crates/iota-framework/docs/iota-system/iota_system.mdx +++ /dev/null @@ -1,1687 +0,0 @@ ---- -title: Module `0x3::iota_system` ---- -import Link from '@docusaurus/Link'; - - -Iota System State Type Upgrade Guide - -IotaSystemState is a thin wrapper around -IotaSystemStateInner that provides a versioned interface. -The -IotaSystemState object has a fixed ID 0x5, and the -IotaSystemStateInner object is stored as a dynamic field. -There are a few different ways to upgrade the -IotaSystemStateInner type: - -The simplest and one that doesn't involve a real upgrade is to just add dynamic fields to the -extra_fields field -of -IotaSystemStateInner or any of its sub type. This is useful when we are in a rush, or making a small change, -or still experimenting a new field. - -To properly upgrade the -IotaSystemStateInner type, we need to ship a new framework that does the following: -1. Define a new -IotaSystemStateInnertype (e.g. -IotaSystemStateInnerV2). -2. Define a data migration function that migrates the old -IotaSystemStateInner to the new one (i.e. IotaSystemStateInnerV2). -3. Replace all uses of -IotaSystemStateInner with -IotaSystemStateInnerV2 in both iota_system.move and iota_system_state_inner.move, -with the exception of the -iota_system_state_inner::create function, which should always return the genesis type. -4. Inside -load_inner_maybe_upgrade function, check the current version in the wrapper, and if it's not the latest version, -call the data migration function to upgrade the inner object. Make sure to also update the version in the wrapper. -A detailed example can be found in iota/tests/framework_upgrades/mock_iota_systems/shallow_upgrade. -Along with the Move change, we also need to update the Rust code to support the new type. This includes: -1. Define a new -IotaSystemStateInner struct type that matches the new Move type, and implement the IotaSystemStateTrait. -2. Update the -IotaSystemState struct to include the new version as a new enum variant. -3. Update the -get_iota_system_state function to handle the new version. -To test that the upgrade will be successful, we need to modify -iota_system_state_production_upgrade_test test in -protocol_version_tests and trigger a real upgrade using the new framework. We will need to keep this directory as old version, -put the new framework in a new directory, and run the test to exercise the upgrade. - -To upgrade Validator type, besides everything above, we also need to: -1. Define a new Validator type (e.g. ValidatorV2). -2. Define a data migration function that migrates the old Validator to the new one (i.e. ValidatorV2). -3. Replace all uses of Validator with ValidatorV2 except the genesis creation function. -4. In validator_wrapper::upgrade_to_latest, check the current version in the wrapper, and if it's not the latest version, -call the data migration function to upgrade it. -In Rust, we also need to add a new case in -get_validator_from_table. -Note that it is possible to upgrade IotaSystemStateInner without upgrading Validator, but not the other way around. -And when we only upgrade IotaSystemStateInner, the version of Validator in the wrapper will not be updated, and hence may become -inconsistent with the version of IotaSystemStateInner. This is fine as long as we don't use the Validator version to determine -the IotaSystemStateInner version, or vice versa. - - -- [Resource `IotaSystemState`](#0x3_iota_system_IotaSystemState) -- [Constants](#@Constants_0) -- [Function `create`](#0x3_iota_system_create) -- [Function `request_add_validator_candidate`](#0x3_iota_system_request_add_validator_candidate) -- [Function `request_remove_validator_candidate`](#0x3_iota_system_request_remove_validator_candidate) -- [Function `request_add_validator`](#0x3_iota_system_request_add_validator) -- [Function `request_remove_validator`](#0x3_iota_system_request_remove_validator) -- [Function `request_set_gas_price`](#0x3_iota_system_request_set_gas_price) -- [Function `set_candidate_validator_gas_price`](#0x3_iota_system_set_candidate_validator_gas_price) -- [Function `request_set_commission_rate`](#0x3_iota_system_request_set_commission_rate) -- [Function `set_candidate_validator_commission_rate`](#0x3_iota_system_set_candidate_validator_commission_rate) -- [Function `request_add_stake`](#0x3_iota_system_request_add_stake) -- [Function `request_add_stake_non_entry`](#0x3_iota_system_request_add_stake_non_entry) -- [Function `request_add_stake_mul_coin`](#0x3_iota_system_request_add_stake_mul_coin) -- [Function `request_withdraw_stake`](#0x3_iota_system_request_withdraw_stake) -- [Function `request_withdraw_stake_non_entry`](#0x3_iota_system_request_withdraw_stake_non_entry) -- [Function `report_validator`](#0x3_iota_system_report_validator) -- [Function `undo_report_validator`](#0x3_iota_system_undo_report_validator) -- [Function `rotate_operation_cap`](#0x3_iota_system_rotate_operation_cap) -- [Function `update_validator_name`](#0x3_iota_system_update_validator_name) -- [Function `update_validator_description`](#0x3_iota_system_update_validator_description) -- [Function `update_validator_image_url`](#0x3_iota_system_update_validator_image_url) -- [Function `update_validator_project_url`](#0x3_iota_system_update_validator_project_url) -- [Function `update_validator_next_epoch_network_address`](#0x3_iota_system_update_validator_next_epoch_network_address) -- [Function `update_candidate_validator_network_address`](#0x3_iota_system_update_candidate_validator_network_address) -- [Function `update_validator_next_epoch_p2p_address`](#0x3_iota_system_update_validator_next_epoch_p2p_address) -- [Function `update_candidate_validator_p2p_address`](#0x3_iota_system_update_candidate_validator_p2p_address) -- [Function `update_validator_next_epoch_primary_address`](#0x3_iota_system_update_validator_next_epoch_primary_address) -- [Function `update_candidate_validator_primary_address`](#0x3_iota_system_update_candidate_validator_primary_address) -- [Function `update_validator_next_epoch_worker_address`](#0x3_iota_system_update_validator_next_epoch_worker_address) -- [Function `update_candidate_validator_worker_address`](#0x3_iota_system_update_candidate_validator_worker_address) -- [Function `update_validator_next_epoch_protocol_pubkey`](#0x3_iota_system_update_validator_next_epoch_protocol_pubkey) -- [Function `update_candidate_validator_protocol_pubkey`](#0x3_iota_system_update_candidate_validator_protocol_pubkey) -- [Function `update_validator_next_epoch_worker_pubkey`](#0x3_iota_system_update_validator_next_epoch_worker_pubkey) -- [Function `update_candidate_validator_worker_pubkey`](#0x3_iota_system_update_candidate_validator_worker_pubkey) -- [Function `update_validator_next_epoch_network_pubkey`](#0x3_iota_system_update_validator_next_epoch_network_pubkey) -- [Function `update_candidate_validator_network_pubkey`](#0x3_iota_system_update_candidate_validator_network_pubkey) -- [Function `pool_exchange_rates`](#0x3_iota_system_pool_exchange_rates) -- [Function `active_validator_addresses`](#0x3_iota_system_active_validator_addresses) -- [Function `advance_epoch`](#0x3_iota_system_advance_epoch) -- [Function `load_system_state`](#0x3_iota_system_load_system_state) -- [Function `load_system_state_mut`](#0x3_iota_system_load_system_state_mut) -- [Function `load_inner_maybe_upgrade`](#0x3_iota_system_load_inner_maybe_upgrade) -- [Function `load_system_timelock_cap`](#0x3_iota_system_load_system_timelock_cap) -- [Function `get_total_iota_supply`](#0x3_iota_system_get_total_iota_supply) - - -

-use 0x1::option;
-use 0x2::balance;
-use 0x2::coin;
-use 0x2::dynamic_field;
-use 0x2::iota;
-use 0x2::object;
-use 0x2::table;
-use 0x2::timelock;
-use 0x2::transfer;
-use 0x2::tx_context;
-use 0x3::iota_system_state_inner;
-use 0x3::staking_pool;
-use 0x3::validator;
-use 0x3::validator_cap;
-
- - - - - -## Resource `IotaSystemState` - - - -

-struct IotaSystemState has key
-
- - - -
-Fields - - -
-
- -id: object::UID -
-
- -
-
- -version: u64 -
-
- -
-
- - -
- - - -## Constants - - - - - - -

-const ENotSystemAddress: u64 = 0;
-
- - - - - - - -

-const EWrongInnerVersion: u64 = 1;
-
- - - - - - - -

-const SYSTEM_TIMELOCK_CAP_DF_KEY: vector<u8> = [115, 121, 115, 95, 116, 105, 109, 101, 108, 111, 99, 107, 95, 99, 97, 112];
-
- - - - - -## Function `create` - -Create a new IotaSystemState object and make it shared. -This function will be called only once in genesis. - - -

-public(friend) fun create(id: object::UID, iota_treasury_cap: iota::IotaTreasuryCap, validators: vector<validator::Validator>, storage_fund: balance::Balance<iota::IOTA>, protocol_version: u64, epoch_start_timestamp_ms: u64, parameters: iota_system_state_inner::SystemParameters, system_timelock_cap: timelock::SystemTimelockCap, ctx: &mut tx_context::TxContext)
-
- - - -
-Implementation - - -

-public(package) fun create(
-    id: UID,
-    iota_treasury_cap: IotaTreasuryCap,
-    validators: vector<Validator>,
-    storage_fund: Balance<IOTA>,
-    protocol_version: u64,
-    epoch_start_timestamp_ms: u64,
-    parameters: SystemParameters,
-    system_timelock_cap: SystemTimelockCap,
-    ctx: &mut TxContext,
-) \{
-    let system_state = iota_system_state_inner::create(
-        iota_treasury_cap,
-        validators,
-        storage_fund,
-        protocol_version,
-        epoch_start_timestamp_ms,
-        parameters,
-        ctx,
-    );
-    let version = iota_system_state_inner::genesis_system_state_version();
-    let mut self = IotaSystemState \{
-        id,
-        version,
-    };
-    dynamic_field::add(&mut self.id, version, system_state);
-    dynamic_field::add(&mut self.id, SYSTEM_TIMELOCK_CAP_DF_KEY, system_timelock_cap);
-    transfer::share_object(self);
-}
-
- - - -
- - - -## Function `request_add_validator_candidate` - -Can be called by anyone who wishes to become a validator candidate and starts accuring delegated -stakes in their staking pool. Once they have at least -MIN_VALIDATOR_JOINING_STAKE amount of stake they -can call -request_add_validator to officially become an active validator at the next epoch. -Aborts if the caller is already a pending or active validator, or a validator candidate. -Note: -proof_of_possession MUST be a valid signature using iota_address and protocol_pubkey_bytes. -To produce a valid PoP, run [fn test_proof_of_possession]. - - -

-public entry fun request_add_validator_candidate(wrapper: &mut iota_system::IotaSystemState, pubkey_bytes: vector<u8>, network_pubkey_bytes: vector<u8>, worker_pubkey_bytes: vector<u8>, proof_of_possession: vector<u8>, name: vector<u8>, description: vector<u8>, image_url: vector<u8>, project_url: vector<u8>, net_address: vector<u8>, p2p_address: vector<u8>, primary_address: vector<u8>, worker_address: vector<u8>, gas_price: u64, commission_rate: u64, ctx: &mut tx_context::TxContext)
-
- - - -
-Implementation - - -

-public entry fun request_add_validator_candidate(
-    wrapper: &mut IotaSystemState,
-    pubkey_bytes: vector<u8>,
-    network_pubkey_bytes: vector<u8>,
-    worker_pubkey_bytes: vector<u8>,
-    proof_of_possession: vector<u8>,
-    name: vector<u8>,
-    description: vector<u8>,
-    image_url: vector<u8>,
-    project_url: vector<u8>,
-    net_address: vector<u8>,
-    p2p_address: vector<u8>,
-    primary_address: vector<u8>,
-    worker_address: vector<u8>,
-    gas_price: u64,
-    commission_rate: u64,
-    ctx: &mut TxContext,
-) \{
-    let self = load_system_state_mut(wrapper);
-    self.request_add_validator_candidate(
-        pubkey_bytes,
-        network_pubkey_bytes,
-        worker_pubkey_bytes,
-        proof_of_possession,
-        name,
-        description,
-        image_url,
-        project_url,
-        net_address,
-        p2p_address,
-        primary_address,
-        worker_address,
-        gas_price,
-        commission_rate,
-        ctx,
-    )
-}
-
- - - -
- - - -## Function `request_remove_validator_candidate` - -Called by a validator candidate to remove themselves from the candidacy. After this call -their staking pool becomes deactivate. - - -

-public entry fun request_remove_validator_candidate(wrapper: &mut iota_system::IotaSystemState, ctx: &mut tx_context::TxContext)
-
- - - -
-Implementation - - -

-public entry fun request_remove_validator_candidate(
-    wrapper: &mut IotaSystemState,
-    ctx: &mut TxContext,
-) \{
-    let self = load_system_state_mut(wrapper);
-    self.request_remove_validator_candidate(ctx)
-}
-
- - - -
- - - -## Function `request_add_validator` - -Called by a validator candidate to add themselves to the active validator set beginning next epoch. -Aborts if the validator is a duplicate with one of the pending or active validators, or if the amount of -stake the validator has doesn't meet the min threshold, or if the number of new validators for the next -epoch has already reached the maximum. - - -

-public entry fun request_add_validator(wrapper: &mut iota_system::IotaSystemState, ctx: &mut tx_context::TxContext)
-
- - - -
-Implementation - - -

-public entry fun request_add_validator(
-    wrapper: &mut IotaSystemState,
-    ctx: &mut TxContext,
-) \{
-    let self = load_system_state_mut(wrapper);
-    self.request_add_validator(ctx)
-}
-
- - - -
- - - -## Function `request_remove_validator` - -A validator can call this function to request a removal in the next epoch. -We use the sender of -ctx to look up the validator -(i.e. sender must match the iota_address in the validator). -At the end of the epoch, the -validator object will be returned to the iota_address -of the validator. - - -

-public entry fun request_remove_validator(wrapper: &mut iota_system::IotaSystemState, ctx: &mut tx_context::TxContext)
-
- - - -
-Implementation - - -

-public entry fun request_remove_validator(
-    wrapper: &mut IotaSystemState,
-    ctx: &mut TxContext,
-) \{
-    let self = load_system_state_mut(wrapper);
-    self.request_remove_validator(ctx)
-}
-
- - - -
- - - -## Function `request_set_gas_price` - -A validator can call this entry function to submit a new gas price quote, to be -used for the reference gas price calculation at the end of the epoch. - - -

-public entry fun request_set_gas_price(wrapper: &mut iota_system::IotaSystemState, cap: &validator_cap::UnverifiedValidatorOperationCap, new_gas_price: u64)
-
- - - -
-Implementation - - -

-public entry fun request_set_gas_price(
-    wrapper: &mut IotaSystemState,
-    cap: &UnverifiedValidatorOperationCap,
-    new_gas_price: u64,
-) \{
-    let self = load_system_state_mut(wrapper);
-    self.request_set_gas_price(cap, new_gas_price)
-}
-
- - - -
- - - -## Function `set_candidate_validator_gas_price` - -This entry function is used to set new gas price for candidate validators - - -

-public entry fun set_candidate_validator_gas_price(wrapper: &mut iota_system::IotaSystemState, cap: &validator_cap::UnverifiedValidatorOperationCap, new_gas_price: u64)
-
- - - -
-Implementation - - -

-public entry fun set_candidate_validator_gas_price(
-    wrapper: &mut IotaSystemState,
-    cap: &UnverifiedValidatorOperationCap,
-    new_gas_price: u64,
-) \{
-    let self = load_system_state_mut(wrapper);
-    self.set_candidate_validator_gas_price(cap, new_gas_price)
-}
-
- - - -
- - - -## Function `request_set_commission_rate` - -A validator can call this entry function to set a new commission rate, updated at the end of -the epoch. - - -

-public entry fun request_set_commission_rate(wrapper: &mut iota_system::IotaSystemState, new_commission_rate: u64, ctx: &mut tx_context::TxContext)
-
- - - -
-Implementation - - -

-public entry fun request_set_commission_rate(
-    wrapper: &mut IotaSystemState,
-    new_commission_rate: u64,
-    ctx: &mut TxContext,
-) \{
-    let self = load_system_state_mut(wrapper);
-    self.request_set_commission_rate(new_commission_rate, ctx)
-}
-
- - - -
- - - -## Function `set_candidate_validator_commission_rate` - -This entry function is used to set new commission rate for candidate validators - - -

-public entry fun set_candidate_validator_commission_rate(wrapper: &mut iota_system::IotaSystemState, new_commission_rate: u64, ctx: &mut tx_context::TxContext)
-
- - - -
-Implementation - - -

-public entry fun set_candidate_validator_commission_rate(
-    wrapper: &mut IotaSystemState,
-    new_commission_rate: u64,
-    ctx: &mut TxContext,
-) \{
-    let self = load_system_state_mut(wrapper);
-    self.set_candidate_validator_commission_rate(new_commission_rate, ctx)
-}
-
- - - -
- - - -## Function `request_add_stake` - -Add stake to a validator's staking pool. - - -

-public entry fun request_add_stake(wrapper: &mut iota_system::IotaSystemState, stake: coin::Coin<iota::IOTA>, validator_address: address, ctx: &mut tx_context::TxContext)
-
- - - -
-Implementation - - -

-public entry fun request_add_stake(
-    wrapper: &mut IotaSystemState,
-    stake: Coin<IOTA>,
-    validator_address: address,
-    ctx: &mut TxContext,
-) \{
-    let staked_iota = request_add_stake_non_entry(wrapper, stake, validator_address, ctx);
-    transfer::public_transfer(staked_iota, ctx.sender());
-}
-
- - - -
- - - -## Function `request_add_stake_non_entry` - -The non-entry version of -request_add_stake, which returns the staked IOTA instead of transferring it to the sender. - - -

-public fun request_add_stake_non_entry(wrapper: &mut iota_system::IotaSystemState, stake: coin::Coin<iota::IOTA>, validator_address: address, ctx: &mut tx_context::TxContext): staking_pool::StakedIota
-
- - - -
-Implementation - - -

-public fun request_add_stake_non_entry(
-    wrapper: &mut IotaSystemState,
-    stake: Coin<IOTA>,
-    validator_address: address,
-    ctx: &mut TxContext,
-): StakedIota \{
-    let self = load_system_state_mut(wrapper);
-    self.request_add_stake(stake, validator_address, ctx)
-}
-
- - - -
- - - -## Function `request_add_stake_mul_coin` - -Add stake to a validator's staking pool using multiple coins. - - -

-public entry fun request_add_stake_mul_coin(wrapper: &mut iota_system::IotaSystemState, stakes: vector<coin::Coin<iota::IOTA>>, stake_amount: option::Option<u64>, validator_address: address, ctx: &mut tx_context::TxContext)
-
- - - -
-Implementation - - -

-public entry fun request_add_stake_mul_coin(
-    wrapper: &mut IotaSystemState,
-    stakes: vector<Coin<IOTA>>,
-    stake_amount: option::Option<u64>,
-    validator_address: address,
-    ctx: &mut TxContext,
-) \{
-    let self = load_system_state_mut(wrapper);
-    let staked_iota = self.request_add_stake_mul_coin(stakes, stake_amount, validator_address, ctx);
-    transfer::public_transfer(staked_iota, ctx.sender());
-}
-
- - - -
- - - -## Function `request_withdraw_stake` - -Withdraw stake from a validator's staking pool. - - -

-public entry fun request_withdraw_stake(wrapper: &mut iota_system::IotaSystemState, staked_iota: staking_pool::StakedIota, ctx: &mut tx_context::TxContext)
-
- - - -
-Implementation - - -

-public entry fun request_withdraw_stake(
-    wrapper: &mut IotaSystemState,
-    staked_iota: StakedIota,
-    ctx: &mut TxContext,
-) \{
-    let withdrawn_stake = request_withdraw_stake_non_entry(wrapper, staked_iota, ctx);
-    transfer::public_transfer(withdrawn_stake.into_coin(ctx), ctx.sender());
-}
-
- - - -
- - - -## Function `request_withdraw_stake_non_entry` - -Non-entry version of -request_withdraw_stake that returns the withdrawn IOTA instead of transferring it to the sender. - - -

-public fun request_withdraw_stake_non_entry(wrapper: &mut iota_system::IotaSystemState, staked_iota: staking_pool::StakedIota, ctx: &mut tx_context::TxContext): balance::Balance<iota::IOTA>
-
- - - -
-Implementation - - -

-public fun request_withdraw_stake_non_entry(
-    wrapper: &mut IotaSystemState,
-    staked_iota: StakedIota,
-    ctx: &mut TxContext,
-) : Balance<IOTA> \{
-    let self = load_system_state_mut(wrapper);
-    self.request_withdraw_stake(staked_iota, ctx)
-}
-
- - - -
- - - -## Function `report_validator` - -Report a validator as a bad or non-performant actor in the system. -Succeeds if all the following are satisfied: -1. both the reporter in -cap and the input -reportee_addr are active validators. -2. reporter and reportee not the same address. -3. the cap object is still valid. -This function is idempotent. - - -

-public entry fun report_validator(wrapper: &mut iota_system::IotaSystemState, cap: &validator_cap::UnverifiedValidatorOperationCap, reportee_addr: address)
-
- - - -
-Implementation - - -

-public entry fun report_validator(
-    wrapper: &mut IotaSystemState,
-    cap: &UnverifiedValidatorOperationCap,
-    reportee_addr: address,
-) \{
-    let self = load_system_state_mut(wrapper);
-    self.report_validator(cap, reportee_addr)
-}
-
- - - -
- - - -## Function `undo_report_validator` - -Undo a -report_validator action. Aborts if -1. the reportee is not a currently active validator or -2. the sender has not previously reported the -reportee_addr, or -3. the cap is not valid - - -

-public entry fun undo_report_validator(wrapper: &mut iota_system::IotaSystemState, cap: &validator_cap::UnverifiedValidatorOperationCap, reportee_addr: address)
-
- - - -
-Implementation - - -

-public entry fun undo_report_validator(
-    wrapper: &mut IotaSystemState,
-    cap: &UnverifiedValidatorOperationCap,
-    reportee_addr: address,
-) \{
-    let self = load_system_state_mut(wrapper);
-    self.undo_report_validator(cap, reportee_addr)
-}
-
- - - -
- - - -## Function `rotate_operation_cap` - -Create a new -UnverifiedValidatorOperationCap, transfer it to the -validator and registers it. The original object is thus revoked. - - -

-public entry fun rotate_operation_cap(self: &mut iota_system::IotaSystemState, ctx: &mut tx_context::TxContext)
-
- - - -
-Implementation - - -

-public entry fun rotate_operation_cap(
-    self: &mut IotaSystemState,
-    ctx: &mut TxContext,
-) \{
-    let self = load_system_state_mut(self);
-    self.rotate_operation_cap(ctx)
-}
-
- - - -
- - - -## Function `update_validator_name` - -Update a validator's name. - - -

-public entry fun update_validator_name(self: &mut iota_system::IotaSystemState, name: vector<u8>, ctx: &tx_context::TxContext)
-
- - - -
-Implementation - - -

-public entry fun update_validator_name(
-    self: &mut IotaSystemState,
-    name: vector<u8>,
-    ctx: &TxContext,
-) \{
-    let self = load_system_state_mut(self);
-    self.update_validator_name(name, ctx)
-}
-
- - - -
- - - -## Function `update_validator_description` - -Update a validator's description - - -

-public entry fun update_validator_description(self: &mut iota_system::IotaSystemState, description: vector<u8>, ctx: &tx_context::TxContext)
-
- - - -
-Implementation - - -

-public entry fun update_validator_description(
-    self: &mut IotaSystemState,
-    description: vector<u8>,
-    ctx: &TxContext,
-) \{
-    let self = load_system_state_mut(self);
-    self.update_validator_description(description, ctx)
-}
-
- - - -
- - - -## Function `update_validator_image_url` - -Update a validator's image url - - -

-public entry fun update_validator_image_url(self: &mut iota_system::IotaSystemState, image_url: vector<u8>, ctx: &tx_context::TxContext)
-
- - - -
-Implementation - - -

-public entry fun update_validator_image_url(
-    self: &mut IotaSystemState,
-    image_url: vector<u8>,
-    ctx: &TxContext,
-) \{
-    let self = load_system_state_mut(self);
-    self.update_validator_image_url(image_url, ctx)
-}
-
- - - -
- - - -## Function `update_validator_project_url` - -Update a validator's project url - - -

-public entry fun update_validator_project_url(self: &mut iota_system::IotaSystemState, project_url: vector<u8>, ctx: &tx_context::TxContext)
-
- - - -
-Implementation - - -

-public entry fun update_validator_project_url(
-    self: &mut IotaSystemState,
-    project_url: vector<u8>,
-    ctx: &TxContext,
-) \{
-    let self = load_system_state_mut(self);
-    self.update_validator_project_url(project_url, ctx)
-}
-
- - - -
- - - -## Function `update_validator_next_epoch_network_address` - -Update a validator's network address. -The change will only take effects starting from the next epoch. - - -

-public entry fun update_validator_next_epoch_network_address(self: &mut iota_system::IotaSystemState, network_address: vector<u8>, ctx: &tx_context::TxContext)
-
- - - -
-Implementation - - -

-public entry fun update_validator_next_epoch_network_address(
-    self: &mut IotaSystemState,
-    network_address: vector<u8>,
-    ctx: &TxContext,
-) \{
-    let self = load_system_state_mut(self);
-    self.update_validator_next_epoch_network_address(network_address, ctx)
-}
-
- - - -
- - - -## Function `update_candidate_validator_network_address` - -Update candidate validator's network address. - - -

-public entry fun update_candidate_validator_network_address(self: &mut iota_system::IotaSystemState, network_address: vector<u8>, ctx: &tx_context::TxContext)
-
- - - -
-Implementation - - -

-public entry fun update_candidate_validator_network_address(
-    self: &mut IotaSystemState,
-    network_address: vector<u8>,
-    ctx: &TxContext,
-) \{
-    let self = load_system_state_mut(self);
-    self.update_candidate_validator_network_address(network_address, ctx)
-}
-
- - - -
- - - -## Function `update_validator_next_epoch_p2p_address` - -Update a validator's p2p address. -The change will only take effects starting from the next epoch. - - -

-public entry fun update_validator_next_epoch_p2p_address(self: &mut iota_system::IotaSystemState, p2p_address: vector<u8>, ctx: &tx_context::TxContext)
-
- - - -
-Implementation - - -

-public entry fun update_validator_next_epoch_p2p_address(
-    self: &mut IotaSystemState,
-    p2p_address: vector<u8>,
-    ctx: &TxContext,
-) \{
-    let self = load_system_state_mut(self);
-    self.update_validator_next_epoch_p2p_address(p2p_address, ctx)
-}
-
- - - -
- - - -## Function `update_candidate_validator_p2p_address` - -Update candidate validator's p2p address. - - -

-public entry fun update_candidate_validator_p2p_address(self: &mut iota_system::IotaSystemState, p2p_address: vector<u8>, ctx: &tx_context::TxContext)
-
- - - -
-Implementation - - -

-public entry fun update_candidate_validator_p2p_address(
-    self: &mut IotaSystemState,
-    p2p_address: vector<u8>,
-    ctx: &TxContext,
-) \{
-    let self = load_system_state_mut(self);
-    self.update_candidate_validator_p2p_address(p2p_address, ctx)
-}
-
- - - -
- - - -## Function `update_validator_next_epoch_primary_address` - -Update a validator's narwhal primary address. -The change will only take effects starting from the next epoch. - - -

-public entry fun update_validator_next_epoch_primary_address(self: &mut iota_system::IotaSystemState, primary_address: vector<u8>, ctx: &tx_context::TxContext)
-
- - - -
-Implementation - - -

-public entry fun update_validator_next_epoch_primary_address(
-    self: &mut IotaSystemState,
-    primary_address: vector<u8>,
-    ctx: &TxContext,
-) \{
-    let self = load_system_state_mut(self);
-    self.update_validator_next_epoch_primary_address(primary_address, ctx)
-}
-
- - - -
- - - -## Function `update_candidate_validator_primary_address` - -Update candidate validator's narwhal primary address. - - -

-public entry fun update_candidate_validator_primary_address(self: &mut iota_system::IotaSystemState, primary_address: vector<u8>, ctx: &tx_context::TxContext)
-
- - - -
-Implementation - - -

-public entry fun update_candidate_validator_primary_address(
-    self: &mut IotaSystemState,
-    primary_address: vector<u8>,
-    ctx: &TxContext,
-) \{
-    let self = load_system_state_mut(self);
-    self.update_candidate_validator_primary_address(primary_address, ctx)
-}
-
- - - -
- - - -## Function `update_validator_next_epoch_worker_address` - -Update a validator's narwhal worker address. -The change will only take effects starting from the next epoch. - - -

-public entry fun update_validator_next_epoch_worker_address(self: &mut iota_system::IotaSystemState, worker_address: vector<u8>, ctx: &tx_context::TxContext)
-
- - - -
-Implementation - - -

-public entry fun update_validator_next_epoch_worker_address(
-    self: &mut IotaSystemState,
-    worker_address: vector<u8>,
-    ctx: &TxContext,
-) \{
-    let self = load_system_state_mut(self);
-    self.update_validator_next_epoch_worker_address(worker_address, ctx)
-}
-
- - - -
- - - -## Function `update_candidate_validator_worker_address` - -Update candidate validator's narwhal worker address. - - -

-public entry fun update_candidate_validator_worker_address(self: &mut iota_system::IotaSystemState, worker_address: vector<u8>, ctx: &tx_context::TxContext)
-
- - - -
-Implementation - - -

-public entry fun update_candidate_validator_worker_address(
-    self: &mut IotaSystemState,
-    worker_address: vector<u8>,
-    ctx: &TxContext,
-) \{
-    let self = load_system_state_mut(self);
-    self.update_candidate_validator_worker_address(worker_address, ctx)
-}
-
- - - -
- - - -## Function `update_validator_next_epoch_protocol_pubkey` - -Update a validator's public key of protocol key and proof of possession. -The change will only take effects starting from the next epoch. - - -

-public entry fun update_validator_next_epoch_protocol_pubkey(self: &mut iota_system::IotaSystemState, protocol_pubkey: vector<u8>, proof_of_possession: vector<u8>, ctx: &tx_context::TxContext)
-
- - - -
-Implementation - - -

-public entry fun update_validator_next_epoch_protocol_pubkey(
-    self: &mut IotaSystemState,
-    protocol_pubkey: vector<u8>,
-    proof_of_possession: vector<u8>,
-    ctx: &TxContext,
-) \{
-    let self = load_system_state_mut(self);
-    self.update_validator_next_epoch_protocol_pubkey(protocol_pubkey, proof_of_possession, ctx)
-}
-
- - - -
- - - -## Function `update_candidate_validator_protocol_pubkey` - -Update candidate validator's public key of protocol key and proof of possession. - - -

-public entry fun update_candidate_validator_protocol_pubkey(self: &mut iota_system::IotaSystemState, protocol_pubkey: vector<u8>, proof_of_possession: vector<u8>, ctx: &tx_context::TxContext)
-
- - - -
-Implementation - - -

-public entry fun update_candidate_validator_protocol_pubkey(
-    self: &mut IotaSystemState,
-    protocol_pubkey: vector<u8>,
-    proof_of_possession: vector<u8>,
-    ctx: &TxContext,
-) \{
-    let self = load_system_state_mut(self);
-    self.update_candidate_validator_protocol_pubkey(protocol_pubkey, proof_of_possession, ctx)
-}
-
- - - -
- - - -## Function `update_validator_next_epoch_worker_pubkey` - -Update a validator's public key of worker key. -The change will only take effects starting from the next epoch. - - -

-public entry fun update_validator_next_epoch_worker_pubkey(self: &mut iota_system::IotaSystemState, worker_pubkey: vector<u8>, ctx: &tx_context::TxContext)
-
- - - -
-Implementation - - -

-public entry fun update_validator_next_epoch_worker_pubkey(
-    self: &mut IotaSystemState,
-    worker_pubkey: vector<u8>,
-    ctx: &TxContext,
-) \{
-    let self = load_system_state_mut(self);
-    self.update_validator_next_epoch_worker_pubkey(worker_pubkey, ctx)
-}
-
- - - -
- - - -## Function `update_candidate_validator_worker_pubkey` - -Update candidate validator's public key of worker key. - - -

-public entry fun update_candidate_validator_worker_pubkey(self: &mut iota_system::IotaSystemState, worker_pubkey: vector<u8>, ctx: &tx_context::TxContext)
-
- - - -
-Implementation - - -

-public entry fun update_candidate_validator_worker_pubkey(
-    self: &mut IotaSystemState,
-    worker_pubkey: vector<u8>,
-    ctx: &TxContext,
-) \{
-    let self = load_system_state_mut(self);
-    self.update_candidate_validator_worker_pubkey(worker_pubkey, ctx)
-}
-
- - - -
- - - -## Function `update_validator_next_epoch_network_pubkey` - -Update a validator's public key of network key. -The change will only take effects starting from the next epoch. - - -

-public entry fun update_validator_next_epoch_network_pubkey(self: &mut iota_system::IotaSystemState, network_pubkey: vector<u8>, ctx: &tx_context::TxContext)
-
- - - -
-Implementation - - -

-public entry fun update_validator_next_epoch_network_pubkey(
-    self: &mut IotaSystemState,
-    network_pubkey: vector<u8>,
-    ctx: &TxContext,
-) \{
-    let self = load_system_state_mut(self);
-    self.update_validator_next_epoch_network_pubkey(network_pubkey, ctx)
-}
-
- - - -
- - - -## Function `update_candidate_validator_network_pubkey` - -Update candidate validator's public key of network key. - - -

-public entry fun update_candidate_validator_network_pubkey(self: &mut iota_system::IotaSystemState, network_pubkey: vector<u8>, ctx: &tx_context::TxContext)
-
- - - -
-Implementation - - -

-public entry fun update_candidate_validator_network_pubkey(
-    self: &mut IotaSystemState,
-    network_pubkey: vector<u8>,
-    ctx: &TxContext,
-) \{
-    let self = load_system_state_mut(self);
-    self.update_candidate_validator_network_pubkey(network_pubkey, ctx)
-}
-
- - - -
- - - -## Function `pool_exchange_rates` - -Getter of the pool token exchange rate of a staking pool. Works for both active and inactive pools. - - -

-public fun pool_exchange_rates(wrapper: &mut iota_system::IotaSystemState, pool_id: &object::ID): &table::Table<u64, staking_pool::PoolTokenExchangeRate>
-
- - - -
-Implementation - - -

-public fun pool_exchange_rates(
-    wrapper: &mut IotaSystemState,
-    pool_id: &ID
-): &Table<u64, PoolTokenExchangeRate>  \{
-    let self = load_system_state_mut(wrapper);
-    self.pool_exchange_rates(pool_id)
-}
-
- - - -
- - - -## Function `active_validator_addresses` - -Getter returning addresses of the currently active validators. - - -

-public fun active_validator_addresses(wrapper: &mut iota_system::IotaSystemState): vector<address>
-
- - - -
-Implementation - - -

-public fun active_validator_addresses(wrapper: &mut IotaSystemState): vector<address> \{
-    let self = load_system_state(wrapper);
-    self.active_validator_addresses()
-}
-
- - - -
- - - -## Function `advance_epoch` - -This function should be called at the end of an epoch, and advances the system to the next epoch. -It does the following things: -1. Add storage charge to the storage fund. -2. Burn the storage rebates from the storage fund. These are already refunded to transaction sender's -gas coins. -3. Mint or burn IOTA tokens depending on whether the validator target reward is greater -or smaller than the computation reward. -4. Distribute the target reward to the validators. -5. Burn any leftover rewards. -6. Update all validators. - - -

-fun advance_epoch(validator_target_reward: u64, storage_charge: balance::Balance<iota::IOTA>, computation_reward: balance::Balance<iota::IOTA>, wrapper: &mut iota_system::IotaSystemState, new_epoch: u64, next_protocol_version: u64, storage_rebate: u64, non_refundable_storage_fee: u64, reward_slashing_rate: u64, epoch_start_timestamp_ms: u64, ctx: &mut tx_context::TxContext): balance::Balance<iota::IOTA>
-
- - - -
-Implementation - - -

-fun advance_epoch(
-    validator_target_reward: u64,
-    storage_charge: Balance<IOTA>,
-    computation_reward: Balance<IOTA>,
-    wrapper: &mut IotaSystemState,
-    new_epoch: u64,
-    next_protocol_version: u64,
-    storage_rebate: u64,
-    non_refundable_storage_fee: u64,
-    reward_slashing_rate: u64, // how much rewards are slashed to punish a validator, in bps.
-    epoch_start_timestamp_ms: u64, // Timestamp of the epoch start
-    ctx: &mut TxContext,
-) : Balance<IOTA> \{
-    let self = load_system_state_mut(wrapper);
-    // Validator will make a special system call with sender set as 0x0.
-    assert!(ctx.sender() == @0x0, ENotSystemAddress);
-    let storage_rebate = self.advance_epoch(
-        new_epoch,
-        next_protocol_version,
-        validator_target_reward,
-        storage_charge,
-        computation_reward,
-        storage_rebate,
-        non_refundable_storage_fee,
-        reward_slashing_rate,
-        epoch_start_timestamp_ms,
-        ctx,
-    );
-
-    storage_rebate
-}
-
- - - -
- - - -## Function `load_system_state` - - - -

-fun load_system_state(self: &mut iota_system::IotaSystemState): &iota_system_state_inner::IotaSystemStateInnerV2
-
- - - -
-Implementation - - -

-fun load_system_state(self: &mut IotaSystemState): &IotaSystemStateInnerV2 \{
-    load_inner_maybe_upgrade(self)
-}
-
- - - -
- - - -## Function `load_system_state_mut` - - - -

-fun load_system_state_mut(self: &mut iota_system::IotaSystemState): &mut iota_system_state_inner::IotaSystemStateInnerV2
-
- - - -
-Implementation - - -

-fun load_system_state_mut(self: &mut IotaSystemState): &mut IotaSystemStateInnerV2 \{
-    load_inner_maybe_upgrade(self)
-}
-
- - - -
- - - -## Function `load_inner_maybe_upgrade` - - - -

-fun load_inner_maybe_upgrade(self: &mut iota_system::IotaSystemState): &mut iota_system_state_inner::IotaSystemStateInnerV2
-
- - - -
-Implementation - - -

-fun load_inner_maybe_upgrade(self: &mut IotaSystemState): &mut IotaSystemStateInnerV2 \{
-    if (self.version == 1) \{
-      let v1: IotaSystemStateInner = dynamic_field::remove(&mut self.id, self.version);
-      let v2 = v1.v1_to_v2();
-      self.version = 2;
-      dynamic_field::add(&mut self.id, self.version, v2);
-    };
-
-    let inner: &mut IotaSystemStateInnerV2 = dynamic_field::borrow_mut(
-        &mut self.id,
-        self.version
-    );
-    assert!(inner.system_state_version() == self.version, EWrongInnerVersion);
-    inner
-}
-
- - - -
- - - -## Function `load_system_timelock_cap` - - - -

-public(friend) fun load_system_timelock_cap(self: &iota_system::IotaSystemState): &timelock::SystemTimelockCap
-
- - - -
-Implementation - - -

-public(package) fun load_system_timelock_cap(self: &IotaSystemState): &SystemTimelockCap \{
-    dynamic_field::borrow(
-        &self.id,
-        SYSTEM_TIMELOCK_CAP_DF_KEY
-    )
-}
-
- - - -
- - - -## Function `get_total_iota_supply` - -Returns the total iota supply. - - -

-public fun get_total_iota_supply(wrapper: &mut iota_system::IotaSystemState): u64
-
- - - -
-Implementation - - -

-public fun get_total_iota_supply(wrapper: &mut IotaSystemState): u64 \{
-    let self = load_system_state(wrapper);
-    self.get_total_iota_supply()
-}
-
- - - -
diff --git a/crates/iota-framework/docs/iota-system/iota_system_state_inner.mdx b/crates/iota-framework/docs/iota-system/iota_system_state_inner.mdx deleted file mode 100644 index f79c2d8683b..00000000000 --- a/crates/iota-framework/docs/iota-system/iota_system_state_inner.mdx +++ /dev/null @@ -1,2819 +0,0 @@ ---- -title: Module `0x3::iota_system_state_inner` ---- -import Link from '@docusaurus/Link'; - - - - -- [Struct `SystemParameters`](#0x3_iota_system_state_inner_SystemParameters) -- [Struct `SystemParametersV2`](#0x3_iota_system_state_inner_SystemParametersV2) -- [Struct `IotaSystemStateInner`](#0x3_iota_system_state_inner_IotaSystemStateInner) -- [Struct `IotaSystemStateInnerV2`](#0x3_iota_system_state_inner_IotaSystemStateInnerV2) -- [Struct `SystemEpochInfoEvent`](#0x3_iota_system_state_inner_SystemEpochInfoEvent) -- [Constants](#@Constants_0) -- [Function `create`](#0x3_iota_system_state_inner_create) -- [Function `create_system_parameters`](#0x3_iota_system_state_inner_create_system_parameters) -- [Function `v1_to_v2`](#0x3_iota_system_state_inner_v1_to_v2) -- [Function `request_add_validator_candidate`](#0x3_iota_system_state_inner_request_add_validator_candidate) -- [Function `request_remove_validator_candidate`](#0x3_iota_system_state_inner_request_remove_validator_candidate) -- [Function `request_add_validator`](#0x3_iota_system_state_inner_request_add_validator) -- [Function `request_remove_validator`](#0x3_iota_system_state_inner_request_remove_validator) -- [Function `request_set_gas_price`](#0x3_iota_system_state_inner_request_set_gas_price) -- [Function `set_candidate_validator_gas_price`](#0x3_iota_system_state_inner_set_candidate_validator_gas_price) -- [Function `request_set_commission_rate`](#0x3_iota_system_state_inner_request_set_commission_rate) -- [Function `set_candidate_validator_commission_rate`](#0x3_iota_system_state_inner_set_candidate_validator_commission_rate) -- [Function `request_add_stake`](#0x3_iota_system_state_inner_request_add_stake) -- [Function `request_add_stake_mul_coin`](#0x3_iota_system_state_inner_request_add_stake_mul_coin) -- [Function `request_withdraw_stake`](#0x3_iota_system_state_inner_request_withdraw_stake) -- [Function `report_validator`](#0x3_iota_system_state_inner_report_validator) -- [Function `undo_report_validator`](#0x3_iota_system_state_inner_undo_report_validator) -- [Function `report_validator_impl`](#0x3_iota_system_state_inner_report_validator_impl) -- [Function `undo_report_validator_impl`](#0x3_iota_system_state_inner_undo_report_validator_impl) -- [Function `rotate_operation_cap`](#0x3_iota_system_state_inner_rotate_operation_cap) -- [Function `update_validator_name`](#0x3_iota_system_state_inner_update_validator_name) -- [Function `update_validator_description`](#0x3_iota_system_state_inner_update_validator_description) -- [Function `update_validator_image_url`](#0x3_iota_system_state_inner_update_validator_image_url) -- [Function `update_validator_project_url`](#0x3_iota_system_state_inner_update_validator_project_url) -- [Function `update_validator_next_epoch_network_address`](#0x3_iota_system_state_inner_update_validator_next_epoch_network_address) -- [Function `update_candidate_validator_network_address`](#0x3_iota_system_state_inner_update_candidate_validator_network_address) -- [Function `update_validator_next_epoch_p2p_address`](#0x3_iota_system_state_inner_update_validator_next_epoch_p2p_address) -- [Function `update_candidate_validator_p2p_address`](#0x3_iota_system_state_inner_update_candidate_validator_p2p_address) -- [Function `update_validator_next_epoch_primary_address`](#0x3_iota_system_state_inner_update_validator_next_epoch_primary_address) -- [Function `update_candidate_validator_primary_address`](#0x3_iota_system_state_inner_update_candidate_validator_primary_address) -- [Function `update_validator_next_epoch_worker_address`](#0x3_iota_system_state_inner_update_validator_next_epoch_worker_address) -- [Function `update_candidate_validator_worker_address`](#0x3_iota_system_state_inner_update_candidate_validator_worker_address) -- [Function `update_validator_next_epoch_protocol_pubkey`](#0x3_iota_system_state_inner_update_validator_next_epoch_protocol_pubkey) -- [Function `update_candidate_validator_protocol_pubkey`](#0x3_iota_system_state_inner_update_candidate_validator_protocol_pubkey) -- [Function `update_validator_next_epoch_worker_pubkey`](#0x3_iota_system_state_inner_update_validator_next_epoch_worker_pubkey) -- [Function `update_candidate_validator_worker_pubkey`](#0x3_iota_system_state_inner_update_candidate_validator_worker_pubkey) -- [Function `update_validator_next_epoch_network_pubkey`](#0x3_iota_system_state_inner_update_validator_next_epoch_network_pubkey) -- [Function `update_candidate_validator_network_pubkey`](#0x3_iota_system_state_inner_update_candidate_validator_network_pubkey) -- [Function `advance_epoch`](#0x3_iota_system_state_inner_advance_epoch) -- [Function `match_computation_reward_to_target_reward`](#0x3_iota_system_state_inner_match_computation_reward_to_target_reward) -- [Function `epoch`](#0x3_iota_system_state_inner_epoch) -- [Function `protocol_version`](#0x3_iota_system_state_inner_protocol_version) -- [Function `system_state_version`](#0x3_iota_system_state_inner_system_state_version) -- [Function `genesis_system_state_version`](#0x3_iota_system_state_inner_genesis_system_state_version) -- [Function `epoch_start_timestamp_ms`](#0x3_iota_system_state_inner_epoch_start_timestamp_ms) -- [Function `validator_stake_amount`](#0x3_iota_system_state_inner_validator_stake_amount) -- [Function `validator_staking_pool_id`](#0x3_iota_system_state_inner_validator_staking_pool_id) -- [Function `validator_staking_pool_mappings`](#0x3_iota_system_state_inner_validator_staking_pool_mappings) -- [Function `get_total_iota_supply`](#0x3_iota_system_state_inner_get_total_iota_supply) -- [Function `get_reporters_of`](#0x3_iota_system_state_inner_get_reporters_of) -- [Function `get_storage_fund_total_balance`](#0x3_iota_system_state_inner_get_storage_fund_total_balance) -- [Function `get_storage_fund_object_rebates`](#0x3_iota_system_state_inner_get_storage_fund_object_rebates) -- [Function `pool_exchange_rates`](#0x3_iota_system_state_inner_pool_exchange_rates) -- [Function `active_validator_addresses`](#0x3_iota_system_state_inner_active_validator_addresses) -- [Function `extract_coin_balance`](#0x3_iota_system_state_inner_extract_coin_balance) - - -

-use 0x1::option;
-use 0x2::bag;
-use 0x2::balance;
-use 0x2::coin;
-use 0x2::event;
-use 0x2::iota;
-use 0x2::object;
-use 0x2::pay;
-use 0x2::table;
-use 0x2::transfer;
-use 0x2::tx_context;
-use 0x2::vec_map;
-use 0x2::vec_set;
-use 0x3::staking_pool;
-use 0x3::storage_fund;
-use 0x3::validator;
-use 0x3::validator_cap;
-use 0x3::validator_set;
-
- - - - - -## Struct `SystemParameters` - -A list of system config parameters. - - -

-struct SystemParameters has store
-
- - - -
-Fields - - -
-
- -epoch_duration_ms: u64 -
-
- The duration of an epoch, in milliseconds. -
-
- -max_validator_count: u64 -
-
- Maximum number of active validators at any moment. - We do not allow the number of validators in any epoch to go above this. -
-
- -min_validator_joining_stake: u64 -
-
- Lower-bound on the amount of stake required to become a validator. -
-
- -validator_low_stake_threshold: u64 -
-
- Validators with stake amount below -validator_low_stake_threshold are considered to - have low stake and will be escorted out of the validator set after being below this - threshold for more than -validator_low_stake_grace_period number of epochs. -
-
- -validator_very_low_stake_threshold: u64 -
-
- Validators with stake below -validator_very_low_stake_threshold will be removed - immediately at epoch change, no grace period. -
-
- -validator_low_stake_grace_period: u64 -
-
- A validator can have stake below -validator_low_stake_threshold - for this many epochs before being kicked out. -
-
- -extra_fields: bag::Bag -
-
- Any extra fields that's not defined statically. -
-
- - -
- - - -## Struct `SystemParametersV2` - -Added min_validator_count. - - -

-struct SystemParametersV2 has store
-
- - - -
-Fields - - -
-
- -epoch_duration_ms: u64 -
-
- The duration of an epoch, in milliseconds. -
-
- -min_validator_count: u64 -
-
- Minimum number of active validators at any moment. -
-
- -max_validator_count: u64 -
-
- Maximum number of active validators at any moment. - We do not allow the number of validators in any epoch to go above this. -
-
- -min_validator_joining_stake: u64 -
-
- Lower-bound on the amount of stake required to become a validator. -
-
- -validator_low_stake_threshold: u64 -
-
- Validators with stake amount below -validator_low_stake_threshold are considered to - have low stake and will be escorted out of the validator set after being below this - threshold for more than -validator_low_stake_grace_period number of epochs. -
-
- -validator_very_low_stake_threshold: u64 -
-
- Validators with stake below -validator_very_low_stake_threshold will be removed - immediately at epoch change, no grace period. -
-
- -validator_low_stake_grace_period: u64 -
-
- A validator can have stake below -validator_low_stake_threshold - for this many epochs before being kicked out. -
-
- -extra_fields: bag::Bag -
-
- Any extra fields that's not defined statically. -
-
- - -
- - - -## Struct `IotaSystemStateInner` - -The top-level object containing all information of the Iota system. - - -

-struct IotaSystemStateInner has store
-
- - - -
-Fields - - -
-
- -epoch: u64 -
-
- The current epoch ID, starting from 0. -
-
- -protocol_version: u64 -
-
- The current protocol version, starting from 1. -
-
- -system_state_version: u64 -
-
- The current version of the system state data structure type. - This is always the same as IotaSystemState.version. Keeping a copy here so that - we know what version it is by inspecting IotaSystemStateInner as well. -
-
- -iota_treasury_cap: iota::IotaTreasuryCap -
-
- The IOTA's TreasuryCap. -
-
- -validators: validator_set::ValidatorSet -
-
- Contains all information about the validators. -
-
- -storage_fund: storage_fund::StorageFund -
-
- The storage fund. -
-
- -parameters: iota_system_state_inner::SystemParameters -
-
- A list of system config parameters. -
-
- -reference_gas_price: u64 -
-
- The reference gas price for the current epoch. -
-
- -validator_report_records: vec_map::VecMap<address, vec_set::VecSet<address>> -
-
- A map storing the records of validator reporting each other. - There is an entry in the map for each validator that has been reported - at least once. The entry VecSet contains all the validators that reported - them. If a validator has never been reported they don't have an entry in this map. - This map persists across epoch: a peer continues being in a reported state until the - reporter doesn't explicitly remove their report. - Note that in case we want to support validator address change in future, - the reports should be based on validator ids -
-
- -safe_mode: bool -
-
- Whether the system is running in a downgraded safe mode due to a non-recoverable bug. - This is set whenever we failed to execute advance_epoch, and ended up executing advance_epoch_safe_mode. - It can be reset once we are able to successfully execute advance_epoch. - The rest of the fields starting with -safe_mode_ are accmulated during safe mode - when advance_epoch_safe_mode is executed. They will eventually be processed once we - are out of safe mode. -
-
- -safe_mode_storage_charges: balance::Balance<iota::IOTA> -
-
- -
-
- -safe_mode_computation_rewards: balance::Balance<iota::IOTA> -
-
- -
-
- -safe_mode_storage_rebates: u64 -
-
- -
-
- -safe_mode_non_refundable_storage_fee: u64 -
-
- -
-
- -epoch_start_timestamp_ms: u64 -
-
- Unix timestamp of the current epoch start -
-
- -extra_fields: bag::Bag -
-
- Any extra fields that's not defined statically. -
-
- - -
- - - -## Struct `IotaSystemStateInnerV2` - -Uses SystemParametersV2 as the parameters. - - -

-struct IotaSystemStateInnerV2 has store
-
- - - -
-Fields - - -
-
- -epoch: u64 -
-
- The current epoch ID, starting from 0. -
-
- -protocol_version: u64 -
-
- The current protocol version, starting from 1. -
-
- -system_state_version: u64 -
-
- The current version of the system state data structure type. - This is always the same as IotaSystemState.version. Keeping a copy here so that - we know what version it is by inspecting IotaSystemStateInner as well. -
-
- -iota_treasury_cap: iota::IotaTreasuryCap -
-
- The IOTA's TreasuryCap. -
-
- -validators: validator_set::ValidatorSet -
-
- Contains all information about the validators. -
-
- -storage_fund: storage_fund::StorageFund -
-
- The storage fund. -
-
- -parameters: iota_system_state_inner::SystemParametersV2 -
-
- A list of system config parameters. -
-
- -reference_gas_price: u64 -
-
- The reference gas price for the current epoch. -
-
- -validator_report_records: vec_map::VecMap<address, vec_set::VecSet<address>> -
-
- A map storing the records of validator reporting each other. - There is an entry in the map for each validator that has been reported - at least once. The entry VecSet contains all the validators that reported - them. If a validator has never been reported they don't have an entry in this map. - This map persists across epoch: a peer continues being in a reported state until the - reporter doesn't explicitly remove their report. - Note that in case we want to support validator address change in future, - the reports should be based on validator ids -
-
- -safe_mode: bool -
-
- Whether the system is running in a downgraded safe mode due to a non-recoverable bug. - This is set whenever we failed to execute advance_epoch, and ended up executing advance_epoch_safe_mode. - It can be reset once we are able to successfully execute advance_epoch. - The rest of the fields starting with -safe_mode_ are accmulated during safe mode - when advance_epoch_safe_mode is executed. They will eventually be processed once we - are out of safe mode. -
-
- -safe_mode_storage_charges: balance::Balance<iota::IOTA> -
-
- -
-
- -safe_mode_computation_rewards: balance::Balance<iota::IOTA> -
-
- -
-
- -safe_mode_storage_rebates: u64 -
-
- -
-
- -safe_mode_non_refundable_storage_fee: u64 -
-
- -
-
- -epoch_start_timestamp_ms: u64 -
-
- Unix timestamp of the current epoch start -
-
- -extra_fields: bag::Bag -
-
- Any extra fields that's not defined statically. -
-
- - -
- - - -## Struct `SystemEpochInfoEvent` - -Event containing system-level epoch information, emitted during -the epoch advancement transaction. - - -

-struct SystemEpochInfoEvent has copy, drop
-
- - - -
-Fields - - -
-
- -epoch: u64 -
-
- -
-
- -protocol_version: u64 -
-
- -
-
- -reference_gas_price: u64 -
-
- -
-
- -total_stake: u64 -
-
- -
-
- -storage_charge: u64 -
-
- -
-
- -storage_rebate: u64 -
-
- -
-
- -storage_fund_balance: u64 -
-
- -
-
- -total_gas_fees: u64 -
-
- -
-
- -total_stake_rewards_distributed: u64 -
-
- -
-
- -burnt_tokens_amount: u64 -
-
- -
-
- -minted_tokens_amount: u64 -
-
- -
-
- - -
- - - -## Constants - - - - - - -

-const ENotSystemAddress: u64 = 2;
-
- - - - - - - -

-const ACTIVE_OR_PENDING_VALIDATOR: u8 = 2;
-
- - - - - - - -

-const ACTIVE_VALIDATOR_ONLY: u8 = 1;
-
- - - - - - - -

-const ANY_VALIDATOR: u8 = 3;
-
- - - - - - - -

-const BASIS_POINT_DENOMINATOR: u128 = 10000;
-
- - - - - - - -

-const EAdvancedToWrongEpoch: u64 = 8;
-
- - - - - - - -

-const EBpsTooLarge: u64 = 5;
-
- - - - - - - -

-const ECannotReportOneself: u64 = 3;
-
- - - - - - - -

-const ELimitExceeded: u64 = 1;
-
- - - - - - - -

-const ENotValidator: u64 = 0;
-
- - - - - - - -

-const EReportRecordNotFound: u64 = 4;
-
- - - - - - - -

-const ESafeModeGasNotProcessed: u64 = 7;
-
- - - - - - - -

-const EStakeWithdrawBeforeActivation: u64 = 6;
-
- - - - - - - -

-const SYSTEM_STATE_VERSION_V1: u64 = 1;
-
- - - - - -## Function `create` - -Create a new IotaSystemState object and make it shared. -This function will be called only once in genesis. - - -

-public(friend) fun create(iota_treasury_cap: iota::IotaTreasuryCap, validators: vector<validator::Validator>, initial_storage_fund: balance::Balance<iota::IOTA>, protocol_version: u64, epoch_start_timestamp_ms: u64, parameters: iota_system_state_inner::SystemParameters, ctx: &mut tx_context::TxContext): iota_system_state_inner::IotaSystemStateInner
-
- - - -
-Implementation - - -

-public(package) fun create(
-    iota_treasury_cap: IotaTreasuryCap,
-    validators: vector<Validator>,
-    initial_storage_fund: Balance<IOTA>,
-    protocol_version: u64,
-    epoch_start_timestamp_ms: u64,
-    parameters: SystemParameters,
-    ctx: &mut TxContext,
-): IotaSystemStateInner \{
-    let validators = validator_set::new(validators, ctx);
-    let reference_gas_price = validators.derive_reference_gas_price();
-    // This type is fixed as it's created at genesis. It should not be updated during type upgrade.
-    let system_state = IotaSystemStateInner \{
-        epoch: 0,
-        protocol_version,
-        system_state_version: genesis_system_state_version(),
-        iota_treasury_cap,
-        validators,
-        storage_fund: storage_fund::new(initial_storage_fund),
-        parameters,
-        reference_gas_price,
-        validator_report_records: vec_map::empty(),
-        safe_mode: false,
-        safe_mode_storage_charges: balance::zero(),
-        safe_mode_computation_rewards: balance::zero(),
-        safe_mode_storage_rebates: 0,
-        safe_mode_non_refundable_storage_fee: 0,
-        epoch_start_timestamp_ms,
-        extra_fields: bag::new(ctx),
-    };
-    system_state
-}
-
- - - -
- - - -## Function `create_system_parameters` - - - -

-public(friend) fun create_system_parameters(epoch_duration_ms: u64, max_validator_count: u64, min_validator_joining_stake: u64, validator_low_stake_threshold: u64, validator_very_low_stake_threshold: u64, validator_low_stake_grace_period: u64, ctx: &mut tx_context::TxContext): iota_system_state_inner::SystemParameters
-
- - - -
-Implementation - - -

-public(package) fun create_system_parameters(
-    epoch_duration_ms: u64,
-
-    // Validator committee parameters
-    max_validator_count: u64,
-    min_validator_joining_stake: u64,
-    validator_low_stake_threshold: u64,
-    validator_very_low_stake_threshold: u64,
-    validator_low_stake_grace_period: u64,
-    ctx: &mut TxContext,
-): SystemParameters \{
-    SystemParameters \{
-        epoch_duration_ms,
-        max_validator_count,
-        min_validator_joining_stake,
-        validator_low_stake_threshold,
-        validator_very_low_stake_threshold,
-        validator_low_stake_grace_period,
-        extra_fields: bag::new(ctx),
-    }
-}
-
- - - -
- - - -## Function `v1_to_v2` - - - -

-public(friend) fun v1_to_v2(self: iota_system_state_inner::IotaSystemStateInner): iota_system_state_inner::IotaSystemStateInnerV2
-
- - - -
-Implementation - - -

-public(package) fun v1_to_v2(self: IotaSystemStateInner): IotaSystemStateInnerV2 \{
-    let IotaSystemStateInner \{
-        epoch,
-        protocol_version,
-        system_state_version: _,
-        iota_treasury_cap,
-        validators,
-        storage_fund,
-        parameters,
-        reference_gas_price,
-        validator_report_records,
-        safe_mode,
-        safe_mode_storage_charges,
-        safe_mode_computation_rewards,
-        safe_mode_storage_rebates,
-        safe_mode_non_refundable_storage_fee,
-        epoch_start_timestamp_ms,
-        extra_fields: state_extra_fields,
-    } = self;
-    let SystemParameters \{
-        epoch_duration_ms,
-        max_validator_count,
-        min_validator_joining_stake,
-        validator_low_stake_threshold,
-        validator_very_low_stake_threshold,
-        validator_low_stake_grace_period,
-        extra_fields: param_extra_fields,
-    } = parameters;
-    IotaSystemStateInnerV2 \{
-        epoch,
-        protocol_version,
-        system_state_version: 2,
-        iota_treasury_cap,
-        validators,
-        storage_fund,
-        parameters: SystemParametersV2 \{
-            epoch_duration_ms,
-            min_validator_count: 4,
-            max_validator_count,
-            min_validator_joining_stake,
-            validator_low_stake_threshold,
-            validator_very_low_stake_threshold,
-            validator_low_stake_grace_period,
-            extra_fields: param_extra_fields,
-        },
-        reference_gas_price,
-        validator_report_records,
-        safe_mode,
-        safe_mode_storage_charges,
-        safe_mode_computation_rewards,
-        safe_mode_storage_rebates,
-        safe_mode_non_refundable_storage_fee,
-        epoch_start_timestamp_ms,
-        extra_fields: state_extra_fields
-    }
-}
-
- - - -
- - - -## Function `request_add_validator_candidate` - -Can be called by anyone who wishes to become a validator candidate and starts accuring delegated -stakes in their staking pool. Once they have at least -MIN_VALIDATOR_JOINING_STAKE amount of stake they -can call -request_add_validator to officially become an active validator at the next epoch. -Aborts if the caller is already a pending or active validator, or a validator candidate. -Note: -proof_of_possession MUST be a valid signature using iota_address and protocol_pubkey_bytes. -To produce a valid PoP, run [fn test_proof_of_possession]. - - -

-public(friend) fun request_add_validator_candidate(self: &mut iota_system_state_inner::IotaSystemStateInnerV2, pubkey_bytes: vector<u8>, network_pubkey_bytes: vector<u8>, worker_pubkey_bytes: vector<u8>, proof_of_possession: vector<u8>, name: vector<u8>, description: vector<u8>, image_url: vector<u8>, project_url: vector<u8>, net_address: vector<u8>, p2p_address: vector<u8>, primary_address: vector<u8>, worker_address: vector<u8>, gas_price: u64, commission_rate: u64, ctx: &mut tx_context::TxContext)
-
- - - -
-Implementation - - -

-public(package) fun request_add_validator_candidate(
-    self: &mut IotaSystemStateInnerV2,
-    pubkey_bytes: vector<u8>,
-    network_pubkey_bytes: vector<u8>,
-    worker_pubkey_bytes: vector<u8>,
-    proof_of_possession: vector<u8>,
-    name: vector<u8>,
-    description: vector<u8>,
-    image_url: vector<u8>,
-    project_url: vector<u8>,
-    net_address: vector<u8>,
-    p2p_address: vector<u8>,
-    primary_address: vector<u8>,
-    worker_address: vector<u8>,
-    gas_price: u64,
-    commission_rate: u64,
-    ctx: &mut TxContext,
-) \{
-    let validator = validator::new(
-        ctx.sender(),
-        pubkey_bytes,
-        network_pubkey_bytes,
-        worker_pubkey_bytes,
-        proof_of_possession,
-        name,
-        description,
-        image_url,
-        project_url,
-        net_address,
-        p2p_address,
-        primary_address,
-        worker_address,
-        gas_price,
-        commission_rate,
-        ctx
-    );
-
-    self.validators.request_add_validator_candidate(validator, ctx);
-}
-
- - - -
- - - -## Function `request_remove_validator_candidate` - -Called by a validator candidate to remove themselves from the candidacy. After this call -their staking pool becomes deactivate. - - -

-public(friend) fun request_remove_validator_candidate(self: &mut iota_system_state_inner::IotaSystemStateInnerV2, ctx: &mut tx_context::TxContext)
-
- - - -
-Implementation - - -

-public(package) fun request_remove_validator_candidate(
-    self: &mut IotaSystemStateInnerV2,
-    ctx: &mut TxContext,
-) \{
-    self.validators.request_remove_validator_candidate(ctx);
-}
-
- - - -
- - - -## Function `request_add_validator` - -Called by a validator candidate to add themselves to the active validator set beginning next epoch. -Aborts if the validator is a duplicate with one of the pending or active validators, or if the amount of -stake the validator has doesn't meet the min threshold, or if the number of new validators for the next -epoch has already reached the maximum. - - -

-public(friend) fun request_add_validator(self: &mut iota_system_state_inner::IotaSystemStateInnerV2, ctx: &tx_context::TxContext)
-
- - - -
-Implementation - - -

-public(package) fun request_add_validator(
-    self: &mut IotaSystemStateInnerV2,
-    ctx: &TxContext,
-) \{
-    assert!(
-        self.validators.next_epoch_validator_count() < self.parameters.max_validator_count,
-        ELimitExceeded,
-    );
-
-    self.validators.request_add_validator(self.parameters.min_validator_joining_stake, ctx);
-}
-
- - - -
- - - -## Function `request_remove_validator` - -A validator can call this function to request a removal in the next epoch. -We use the sender of -ctx to look up the validator -(i.e. sender must match the iota_address in the validator). -At the end of the epoch, the -validator object will be returned to the iota_address -of the validator. - - -

-public(friend) fun request_remove_validator(self: &mut iota_system_state_inner::IotaSystemStateInnerV2, ctx: &tx_context::TxContext)
-
- - - -
-Implementation - - -

-public(package) fun request_remove_validator(
-    self: &mut IotaSystemStateInnerV2,
-    ctx: &TxContext,
-) \{
-    // Only check min validator condition if the current number of validators satisfy the constraint.
-    // This is so that if we somehow already are in a state where we have less than min validators, it no longer matters
-    // and is ok to stay so. This is useful for a test setup.
-    if (self.validators.active_validators().length() >= self.parameters.min_validator_count) \{
-        assert!(
-            self.validators.next_epoch_validator_count() > self.parameters.min_validator_count,
-            ELimitExceeded,
-        );
-    };
-
-    self.validators.request_remove_validator(ctx)
-}
-
- - - -
- - - -## Function `request_set_gas_price` - -A validator can call this function to submit a new gas price quote, to be -used for the reference gas price calculation at the end of the epoch. - - -

-public(friend) fun request_set_gas_price(self: &mut iota_system_state_inner::IotaSystemStateInnerV2, cap: &validator_cap::UnverifiedValidatorOperationCap, new_gas_price: u64)
-
- - - -
-Implementation - - -

-public(package) fun request_set_gas_price(
-    self: &mut IotaSystemStateInnerV2,
-    cap: &UnverifiedValidatorOperationCap,
-    new_gas_price: u64,
-) \{
-    // Verify the represented address is an active or pending validator, and the capability is still valid.
-    let verified_cap = self.validators.verify_cap(cap, ACTIVE_OR_PENDING_VALIDATOR);
-    let validator = self.validators.get_validator_mut_with_verified_cap(&verified_cap, false /* include_candidate */);
-
-    validator.request_set_gas_price(verified_cap, new_gas_price);
-}
-
- - - -
- - - -## Function `set_candidate_validator_gas_price` - -This function is used to set new gas price for candidate validators - - -

-public(friend) fun set_candidate_validator_gas_price(self: &mut iota_system_state_inner::IotaSystemStateInnerV2, cap: &validator_cap::UnverifiedValidatorOperationCap, new_gas_price: u64)
-
- - - -
-Implementation - - -

-public(package) fun set_candidate_validator_gas_price(
-    self: &mut IotaSystemStateInnerV2,
-    cap: &UnverifiedValidatorOperationCap,
-    new_gas_price: u64,
-) \{
-    // Verify the represented address is an active or pending validator, and the capability is still valid.
-    let verified_cap = self.validators.verify_cap(cap, ANY_VALIDATOR);
-    let candidate = self.validators.get_validator_mut_with_verified_cap(&verified_cap, true /* include_candidate */);
-    candidate.set_candidate_gas_price(verified_cap, new_gas_price)
-}
-
- - - -
- - - -## Function `request_set_commission_rate` - -A validator can call this function to set a new commission rate, updated at the end of -the epoch. - - -

-public(friend) fun request_set_commission_rate(self: &mut iota_system_state_inner::IotaSystemStateInnerV2, new_commission_rate: u64, ctx: &tx_context::TxContext)
-
- - - -
-Implementation - - -

-public(package) fun request_set_commission_rate(
-    self: &mut IotaSystemStateInnerV2,
-    new_commission_rate: u64,
-    ctx: &TxContext,
-) \{
-    self.validators.request_set_commission_rate(
-        new_commission_rate,
-        ctx
-    )
-}
-
- - - -
- - - -## Function `set_candidate_validator_commission_rate` - -This function is used to set new commission rate for candidate validators - - -

-public(friend) fun set_candidate_validator_commission_rate(self: &mut iota_system_state_inner::IotaSystemStateInnerV2, new_commission_rate: u64, ctx: &tx_context::TxContext)
-
- - - -
-Implementation - - -

-public(package) fun set_candidate_validator_commission_rate(
-    self: &mut IotaSystemStateInnerV2,
-    new_commission_rate: u64,
-    ctx: &TxContext,
-) \{
-    let candidate = self.validators.get_validator_mut_with_ctx_including_candidates(ctx);
-    candidate.set_candidate_commission_rate(new_commission_rate)
-}
-
- - - -
- - - -## Function `request_add_stake` - -Add stake to a validator's staking pool. - - -

-public(friend) fun request_add_stake(self: &mut iota_system_state_inner::IotaSystemStateInnerV2, stake: coin::Coin<iota::IOTA>, validator_address: address, ctx: &mut tx_context::TxContext): staking_pool::StakedIota
-
- - - -
-Implementation - - -

-public(package) fun request_add_stake(
-    self: &mut IotaSystemStateInnerV2,
-    stake: Coin<IOTA>,
-    validator_address: address,
-    ctx: &mut TxContext,
-) : StakedIota \{
-    self.validators.request_add_stake(
-        validator_address,
-        stake.into_balance(),
-        ctx,
-    )
-}
-
- - - -
- - - -## Function `request_add_stake_mul_coin` - -Add stake to a validator's staking pool using multiple coins. - - -

-public(friend) fun request_add_stake_mul_coin(self: &mut iota_system_state_inner::IotaSystemStateInnerV2, stakes: vector<coin::Coin<iota::IOTA>>, stake_amount: option::Option<u64>, validator_address: address, ctx: &mut tx_context::TxContext): staking_pool::StakedIota
-
- - - -
-Implementation - - -

-public(package) fun request_add_stake_mul_coin(
-    self: &mut IotaSystemStateInnerV2,
-    stakes: vector<Coin<IOTA>>,
-    stake_amount: option::Option<u64>,
-    validator_address: address,
-    ctx: &mut TxContext,
-) : StakedIota \{
-    let balance = extract_coin_balance(stakes, stake_amount, ctx);
-    self.validators.request_add_stake(validator_address, balance, ctx)
-}
-
- - - -
- - - -## Function `request_withdraw_stake` - -Withdraw some portion of a stake from a validator's staking pool. - - -

-public(friend) fun request_withdraw_stake(self: &mut iota_system_state_inner::IotaSystemStateInnerV2, staked_iota: staking_pool::StakedIota, ctx: &tx_context::TxContext): balance::Balance<iota::IOTA>
-
- - - -
-Implementation - - -

-public(package) fun request_withdraw_stake(
-    self: &mut IotaSystemStateInnerV2,
-    staked_iota: StakedIota,
-    ctx: &TxContext,
-) : Balance<IOTA> \{
-    assert!(
-        stake_activation_epoch(&staked_iota) <= ctx.epoch(),
-        EStakeWithdrawBeforeActivation
-    );
-    self.validators.request_withdraw_stake(staked_iota, ctx)
-}
-
- - - -
- - - -## Function `report_validator` - -Report a validator as a bad or non-performant actor in the system. -Succeeds if all the following are satisfied: -1. both the reporter in -cap and the input -reportee_addr are active validators. -2. reporter and reportee not the same address. -3. the cap object is still valid. -This function is idempotent. - - -

-public(friend) fun report_validator(self: &mut iota_system_state_inner::IotaSystemStateInnerV2, cap: &validator_cap::UnverifiedValidatorOperationCap, reportee_addr: address)
-
- - - -
-Implementation - - -

-public(package) fun report_validator(
-    self: &mut IotaSystemStateInnerV2,
-    cap: &UnverifiedValidatorOperationCap,
-    reportee_addr: address,
-) \{
-    // Reportee needs to be an active validator
-    assert!(self.validators.is_active_validator_by_iota_address(reportee_addr), ENotValidator);
-    // Verify the represented reporter address is an active validator, and the capability is still valid.
-    let verified_cap = self.validators.verify_cap(cap, ACTIVE_VALIDATOR_ONLY);
-    report_validator_impl(verified_cap, reportee_addr, &mut self.validator_report_records);
-}
-
- - - -
- - - -## Function `undo_report_validator` - -Undo a -report_validator action. Aborts if -1. the reportee is not a currently active validator or -2. the sender has not previously reported the -reportee_addr, or -3. the cap is not valid - - -

-public(friend) fun undo_report_validator(self: &mut iota_system_state_inner::IotaSystemStateInnerV2, cap: &validator_cap::UnverifiedValidatorOperationCap, reportee_addr: address)
-
- - - -
-Implementation - - -

-public(package) fun undo_report_validator(
-    self: &mut IotaSystemStateInnerV2,
-    cap: &UnverifiedValidatorOperationCap,
-    reportee_addr: address,
-) \{
-    let verified_cap = self.validators.verify_cap(cap, ACTIVE_VALIDATOR_ONLY);
-    undo_report_validator_impl(verified_cap, reportee_addr, &mut self.validator_report_records);
-}
-
- - - -
- - - -## Function `report_validator_impl` - - - -

-fun report_validator_impl(verified_cap: validator_cap::ValidatorOperationCap, reportee_addr: address, validator_report_records: &mut vec_map::VecMap<address, vec_set::VecSet<address>>)
-
- - - -
-Implementation - - -

-fun report_validator_impl(
-    verified_cap: ValidatorOperationCap,
-    reportee_addr: address,
-    validator_report_records: &mut VecMap<address, VecSet<address>>,
-) \{
-    let reporter_address = *verified_cap.verified_operation_cap_address();
-    assert!(reporter_address != reportee_addr, ECannotReportOneself);
-    if (!validator_report_records.contains(&reportee_addr)) \{
-        validator_report_records.insert(reportee_addr, vec_set::singleton(reporter_address));
-    } else \{
-        let reporters = validator_report_records.get_mut(&reportee_addr);
-        if (!reporters.contains(&reporter_address)) \{
-            reporters.insert(reporter_address);
-        }
-    }
-}
-
- - - -
- - - -## Function `undo_report_validator_impl` - - - -

-fun undo_report_validator_impl(verified_cap: validator_cap::ValidatorOperationCap, reportee_addr: address, validator_report_records: &mut vec_map::VecMap<address, vec_set::VecSet<address>>)
-
- - - -
-Implementation - - -

-fun undo_report_validator_impl(
-    verified_cap: ValidatorOperationCap,
-    reportee_addr: address,
-    validator_report_records: &mut VecMap<address, VecSet<address>>,
-) \{
-    assert!(validator_report_records.contains(&reportee_addr), EReportRecordNotFound);
-    let reporters = validator_report_records.get_mut(&reportee_addr);
-
-    let reporter_addr = *verified_cap.verified_operation_cap_address();
-    assert!(reporters.contains(&reporter_addr), EReportRecordNotFound);
-
-    reporters.remove(&reporter_addr);
-    if (reporters.is_empty()) \{
-        validator_report_records.remove(&reportee_addr);
-    }
-}
-
- - - -
- - - -## Function `rotate_operation_cap` - -Create a new -UnverifiedValidatorOperationCap, transfer it to the -validator and registers it. The original object is thus revoked. - - -

-public(friend) fun rotate_operation_cap(self: &mut iota_system_state_inner::IotaSystemStateInnerV2, ctx: &mut tx_context::TxContext)
-
- - - -
-Implementation - - -

-public(package) fun rotate_operation_cap(
-    self: &mut IotaSystemStateInnerV2,
-    ctx: &mut TxContext,
-) \{
-    let validator = self.validators.get_validator_mut_with_ctx_including_candidates(ctx);
-    validator.new_unverified_validator_operation_cap_and_transfer(ctx);
-}
-
- - - -
- - - -## Function `update_validator_name` - -Update a validator's name. - - -

-public(friend) fun update_validator_name(self: &mut iota_system_state_inner::IotaSystemStateInnerV2, name: vector<u8>, ctx: &tx_context::TxContext)
-
- - - -
-Implementation - - -

-public(package) fun update_validator_name(
-    self: &mut IotaSystemStateInnerV2,
-    name: vector<u8>,
-    ctx: &TxContext,
-) \{
-    let validator = self.validators.get_validator_mut_with_ctx_including_candidates(ctx);
-
-    validator.update_name(name);
-}
-
- - - -
- - - -## Function `update_validator_description` - -Update a validator's description - - -

-public(friend) fun update_validator_description(self: &mut iota_system_state_inner::IotaSystemStateInnerV2, description: vector<u8>, ctx: &tx_context::TxContext)
-
- - - -
-Implementation - - -

-public(package) fun update_validator_description(
-    self: &mut IotaSystemStateInnerV2,
-    description: vector<u8>,
-    ctx: &TxContext,
-) \{
-    let validator = self.validators.get_validator_mut_with_ctx_including_candidates(ctx);
-    validator.update_description(description);
-}
-
- - - -
- - - -## Function `update_validator_image_url` - -Update a validator's image url - - -

-public(friend) fun update_validator_image_url(self: &mut iota_system_state_inner::IotaSystemStateInnerV2, image_url: vector<u8>, ctx: &tx_context::TxContext)
-
- - - -
-Implementation - - -

-public(package) fun update_validator_image_url(
-    self: &mut IotaSystemStateInnerV2,
-    image_url: vector<u8>,
-    ctx: &TxContext,
-) \{
-    let validator = self.validators.get_validator_mut_with_ctx_including_candidates(ctx);
-    validator.update_image_url(image_url);
-}
-
- - - -
- - - -## Function `update_validator_project_url` - -Update a validator's project url - - -

-public(friend) fun update_validator_project_url(self: &mut iota_system_state_inner::IotaSystemStateInnerV2, project_url: vector<u8>, ctx: &tx_context::TxContext)
-
- - - -
-Implementation - - -

-public(package) fun update_validator_project_url(
-    self: &mut IotaSystemStateInnerV2,
-    project_url: vector<u8>,
-    ctx: &TxContext,
-) \{
-    let validator = self.validators.get_validator_mut_with_ctx_including_candidates(ctx);
-    validator.update_project_url(project_url);
-}
-
- - - -
- - - -## Function `update_validator_next_epoch_network_address` - -Update a validator's network address. -The change will only take effects starting from the next epoch. - - -

-public(friend) fun update_validator_next_epoch_network_address(self: &mut iota_system_state_inner::IotaSystemStateInnerV2, network_address: vector<u8>, ctx: &tx_context::TxContext)
-
- - - -
-Implementation - - -

-public(package) fun update_validator_next_epoch_network_address(
-    self: &mut IotaSystemStateInnerV2,
-    network_address: vector<u8>,
-    ctx: &TxContext,
-) \{
-    let validator = self.validators.get_validator_mut_with_ctx(ctx);
-    validator.update_next_epoch_network_address(network_address);
-    let validator :&Validator = validator; // Force immutability for the following call
-    self.validators.assert_no_pending_or_active_duplicates(validator);
-}
-
- - - -
- - - -## Function `update_candidate_validator_network_address` - -Update candidate validator's network address. - - -

-public(friend) fun update_candidate_validator_network_address(self: &mut iota_system_state_inner::IotaSystemStateInnerV2, network_address: vector<u8>, ctx: &tx_context::TxContext)
-
- - - -
-Implementation - - -

-public(package) fun update_candidate_validator_network_address(
-    self: &mut IotaSystemStateInnerV2,
-    network_address: vector<u8>,
-    ctx: &TxContext,
-) \{
-    let candidate = self.validators.get_validator_mut_with_ctx_including_candidates(ctx);
-    candidate.update_candidate_network_address(network_address);
-}
-
- - - -
- - - -## Function `update_validator_next_epoch_p2p_address` - -Update a validator's p2p address. -The change will only take effects starting from the next epoch. - - -

-public(friend) fun update_validator_next_epoch_p2p_address(self: &mut iota_system_state_inner::IotaSystemStateInnerV2, p2p_address: vector<u8>, ctx: &tx_context::TxContext)
-
- - - -
-Implementation - - -

-public(package) fun update_validator_next_epoch_p2p_address(
-    self: &mut IotaSystemStateInnerV2,
-    p2p_address: vector<u8>,
-    ctx: &TxContext,
-) \{
-    let validator = self.validators.get_validator_mut_with_ctx(ctx);
-    validator.update_next_epoch_p2p_address(p2p_address);
-    let validator :&Validator = validator; // Force immutability for the following call
-    self.validators.assert_no_pending_or_active_duplicates(validator);
-}
-
- - - -
- - - -## Function `update_candidate_validator_p2p_address` - -Update candidate validator's p2p address. - - -

-public(friend) fun update_candidate_validator_p2p_address(self: &mut iota_system_state_inner::IotaSystemStateInnerV2, p2p_address: vector<u8>, ctx: &tx_context::TxContext)
-
- - - -
-Implementation - - -

-public(package) fun update_candidate_validator_p2p_address(
-    self: &mut IotaSystemStateInnerV2,
-    p2p_address: vector<u8>,
-    ctx: &TxContext,
-) \{
-    let candidate = self.validators.get_validator_mut_with_ctx_including_candidates(ctx);
-    candidate.update_candidate_p2p_address(p2p_address);
-}
-
- - - -
- - - -## Function `update_validator_next_epoch_primary_address` - -Update a validator's narwhal primary address. -The change will only take effects starting from the next epoch. - - -

-public(friend) fun update_validator_next_epoch_primary_address(self: &mut iota_system_state_inner::IotaSystemStateInnerV2, primary_address: vector<u8>, ctx: &tx_context::TxContext)
-
- - - -
-Implementation - - -

-public(package) fun update_validator_next_epoch_primary_address(
-    self: &mut IotaSystemStateInnerV2,
-    primary_address: vector<u8>,
-    ctx: &TxContext,
-) \{
-    let validator = self.validators.get_validator_mut_with_ctx(ctx);
-    validator.update_next_epoch_primary_address(primary_address);
-}
-
- - - -
- - - -## Function `update_candidate_validator_primary_address` - -Update candidate validator's narwhal primary address. - - -

-public(friend) fun update_candidate_validator_primary_address(self: &mut iota_system_state_inner::IotaSystemStateInnerV2, primary_address: vector<u8>, ctx: &tx_context::TxContext)
-
- - - -
-Implementation - - -

-public(package) fun update_candidate_validator_primary_address(
-    self: &mut IotaSystemStateInnerV2,
-    primary_address: vector<u8>,
-    ctx: &TxContext,
-) \{
-    let candidate = self.validators.get_validator_mut_with_ctx_including_candidates(ctx);
-    candidate.update_candidate_primary_address(primary_address);
-}
-
- - - -
- - - -## Function `update_validator_next_epoch_worker_address` - -Update a validator's narwhal worker address. -The change will only take effects starting from the next epoch. - - -

-public(friend) fun update_validator_next_epoch_worker_address(self: &mut iota_system_state_inner::IotaSystemStateInnerV2, worker_address: vector<u8>, ctx: &tx_context::TxContext)
-
- - - -
-Implementation - - -

-public(package) fun update_validator_next_epoch_worker_address(
-    self: &mut IotaSystemStateInnerV2,
-    worker_address: vector<u8>,
-    ctx: &TxContext,
-) \{
-    let validator = self.validators.get_validator_mut_with_ctx(ctx);
-    validator.update_next_epoch_worker_address(worker_address);
-}
-
- - - -
- - - -## Function `update_candidate_validator_worker_address` - -Update candidate validator's narwhal worker address. - - -

-public(friend) fun update_candidate_validator_worker_address(self: &mut iota_system_state_inner::IotaSystemStateInnerV2, worker_address: vector<u8>, ctx: &tx_context::TxContext)
-
- - - -
-Implementation - - -

-public(package) fun update_candidate_validator_worker_address(
-    self: &mut IotaSystemStateInnerV2,
-    worker_address: vector<u8>,
-    ctx: &TxContext,
-) \{
-    let candidate = self.validators.get_validator_mut_with_ctx_including_candidates(ctx);
-    candidate.update_candidate_worker_address(worker_address);
-}
-
- - - -
- - - -## Function `update_validator_next_epoch_protocol_pubkey` - -Update a validator's public key of protocol key and proof of possession. -The change will only take effects starting from the next epoch. - - -

-public(friend) fun update_validator_next_epoch_protocol_pubkey(self: &mut iota_system_state_inner::IotaSystemStateInnerV2, protocol_pubkey: vector<u8>, proof_of_possession: vector<u8>, ctx: &tx_context::TxContext)
-
- - - -
-Implementation - - -

-public(package) fun update_validator_next_epoch_protocol_pubkey(
-    self: &mut IotaSystemStateInnerV2,
-    protocol_pubkey: vector<u8>,
-    proof_of_possession: vector<u8>,
-    ctx: &TxContext,
-) \{
-    let validator = self.validators.get_validator_mut_with_ctx(ctx);
-    validator.update_next_epoch_protocol_pubkey(protocol_pubkey, proof_of_possession);
-    let validator :&Validator = validator; // Force immutability for the following call
-    self.validators.assert_no_pending_or_active_duplicates(validator);
-}
-
- - - -
- - - -## Function `update_candidate_validator_protocol_pubkey` - -Update candidate validator's public key of protocol key and proof of possession. - - -

-public(friend) fun update_candidate_validator_protocol_pubkey(self: &mut iota_system_state_inner::IotaSystemStateInnerV2, protocol_pubkey: vector<u8>, proof_of_possession: vector<u8>, ctx: &tx_context::TxContext)
-
- - - -
-Implementation - - -

-public(package) fun update_candidate_validator_protocol_pubkey(
-    self: &mut IotaSystemStateInnerV2,
-    protocol_pubkey: vector<u8>,
-    proof_of_possession: vector<u8>,
-    ctx: &TxContext,
-) \{
-    let candidate = self.validators.get_validator_mut_with_ctx_including_candidates(ctx);
-    candidate.update_candidate_protocol_pubkey(protocol_pubkey, proof_of_possession);
-}
-
- - - -
- - - -## Function `update_validator_next_epoch_worker_pubkey` - -Update a validator's public key of worker key. -The change will only take effects starting from the next epoch. - - -

-public(friend) fun update_validator_next_epoch_worker_pubkey(self: &mut iota_system_state_inner::IotaSystemStateInnerV2, worker_pubkey: vector<u8>, ctx: &tx_context::TxContext)
-
- - - -
-Implementation - - -

-public(package) fun update_validator_next_epoch_worker_pubkey(
-    self: &mut IotaSystemStateInnerV2,
-    worker_pubkey: vector<u8>,
-    ctx: &TxContext,
-) \{
-    let validator = self.validators.get_validator_mut_with_ctx(ctx);
-    validator.update_next_epoch_worker_pubkey(worker_pubkey);
-    let validator :&Validator = validator; // Force immutability for the following call
-    self.validators.assert_no_pending_or_active_duplicates(validator);
-}
-
- - - -
- - - -## Function `update_candidate_validator_worker_pubkey` - -Update candidate validator's public key of worker key. - - -

-public(friend) fun update_candidate_validator_worker_pubkey(self: &mut iota_system_state_inner::IotaSystemStateInnerV2, worker_pubkey: vector<u8>, ctx: &tx_context::TxContext)
-
- - - -
-Implementation - - -

-public(package) fun update_candidate_validator_worker_pubkey(
-    self: &mut IotaSystemStateInnerV2,
-    worker_pubkey: vector<u8>,
-    ctx: &TxContext,
-) \{
-    let candidate = self.validators.get_validator_mut_with_ctx_including_candidates(ctx);
-    candidate.update_candidate_worker_pubkey(worker_pubkey);
-}
-
- - - -
- - - -## Function `update_validator_next_epoch_network_pubkey` - -Update a validator's public key of network key. -The change will only take effects starting from the next epoch. - - -

-public(friend) fun update_validator_next_epoch_network_pubkey(self: &mut iota_system_state_inner::IotaSystemStateInnerV2, network_pubkey: vector<u8>, ctx: &tx_context::TxContext)
-
- - - -
-Implementation - - -

-public(package) fun update_validator_next_epoch_network_pubkey(
-    self: &mut IotaSystemStateInnerV2,
-    network_pubkey: vector<u8>,
-    ctx: &TxContext,
-) \{
-    let validator = self.validators.get_validator_mut_with_ctx(ctx);
-    validator.update_next_epoch_network_pubkey(network_pubkey);
-    let validator :&Validator = validator; // Force immutability for the following call
-    self.validators.assert_no_pending_or_active_duplicates(validator);
-}
-
- - - -
- - - -## Function `update_candidate_validator_network_pubkey` - -Update candidate validator's public key of network key. - - -

-public(friend) fun update_candidate_validator_network_pubkey(self: &mut iota_system_state_inner::IotaSystemStateInnerV2, network_pubkey: vector<u8>, ctx: &tx_context::TxContext)
-
- - - -
-Implementation - - -

-public(package) fun update_candidate_validator_network_pubkey(
-    self: &mut IotaSystemStateInnerV2,
-    network_pubkey: vector<u8>,
-    ctx: &TxContext,
-) \{
-    let candidate = self.validators.get_validator_mut_with_ctx_including_candidates(ctx);
-    candidate.update_candidate_network_pubkey(network_pubkey);
-}
-
- - - -
- - - -## Function `advance_epoch` - -This function should be called at the end of an epoch, and advances the system to the next epoch. -It does the following things: -1. Add storage charge to the storage fund. -2. Burn the storage rebates from the storage fund. These are already refunded to transaction sender's -gas coins. -3. Mint or burn IOTA tokens depending on whether the validator target reward is greater -or smaller than the computation reward. -4. Distribute the target reward to the validators. -5. Burn any leftover rewards. -6. Update all validators. - - -

-public(friend) fun advance_epoch(self: &mut iota_system_state_inner::IotaSystemStateInnerV2, new_epoch: u64, next_protocol_version: u64, validator_target_reward: u64, storage_charge: balance::Balance<iota::IOTA>, computation_reward: balance::Balance<iota::IOTA>, storage_rebate_amount: u64, non_refundable_storage_fee_amount: u64, reward_slashing_rate: u64, epoch_start_timestamp_ms: u64, ctx: &mut tx_context::TxContext): balance::Balance<iota::IOTA>
-
- - - -
-Implementation - - -

-public(package) fun advance_epoch(
-    self: &mut IotaSystemStateInnerV2,
-    new_epoch: u64,
-    next_protocol_version: u64,
-    validator_target_reward: u64,
-    mut storage_charge: Balance<IOTA>,
-    mut computation_reward: Balance<IOTA>,
-    mut storage_rebate_amount: u64,
-    mut non_refundable_storage_fee_amount: u64,
-    reward_slashing_rate: u64, // how much rewards are slashed to punish a validator, in bps.
-    epoch_start_timestamp_ms: u64, // Timestamp of the epoch start
-    ctx: &mut TxContext,
-) : Balance<IOTA> \{
-    self.epoch_start_timestamp_ms = epoch_start_timestamp_ms;
-
-    let bps_denominator_u64 = BASIS_POINT_DENOMINATOR as u64;
-    // Rates can't be higher than 100%.
-    assert!(reward_slashing_rate <= bps_denominator_u64, EBpsTooLarge);
-
-    // Accumulate the gas summary during safe_mode before processing any rewards:
-    let safe_mode_storage_charges = self.safe_mode_storage_charges.withdraw_all();
-    storage_charge.join(safe_mode_storage_charges);
-    let safe_mode_computation_rewards = self.safe_mode_computation_rewards.withdraw_all();
-    computation_reward.join(safe_mode_computation_rewards);
-    storage_rebate_amount = storage_rebate_amount + self.safe_mode_storage_rebates;
-    self.safe_mode_storage_rebates = 0;
-    non_refundable_storage_fee_amount = non_refundable_storage_fee_amount + self.safe_mode_non_refundable_storage_fee;
-    self.safe_mode_non_refundable_storage_fee = 0;
-
-    let storage_charge_value = storage_charge.value();
-    let computation_charge = computation_reward.value();
-
-    let (mut total_validator_rewards, minted_tokens_amount, mut burnt_tokens_amount) = match_computation_reward_to_target_reward(
-        validator_target_reward,
-        computation_reward,
-        &mut self.iota_treasury_cap,
-        ctx
-    );
-
-    self.epoch = self.epoch + 1;
-    // Sanity check to make sure we are advancing to the right epoch.
-    assert!(new_epoch == self.epoch, EAdvancedToWrongEpoch);
-
-    let total_validator_rewards_amount_before_distribution = total_validator_rewards.value();
-
-    self.validators.advance_epoch(
-        &mut total_validator_rewards,
-        &mut self.validator_report_records,
-        reward_slashing_rate,
-        self.parameters.validator_low_stake_threshold,
-        self.parameters.validator_very_low_stake_threshold,
-        self.parameters.validator_low_stake_grace_period,
-        ctx,
-    );
-
-    let new_total_stake = self.validators.total_stake();
-
-    let remaining_validator_rewards_amount_after_distribution = total_validator_rewards.value();
-    let total_validator_rewards_distributed = total_validator_rewards_amount_before_distribution - remaining_validator_rewards_amount_after_distribution;
-
-    self.protocol_version = next_protocol_version;
-
-    // Derive the reference gas price for the new epoch
-    self.reference_gas_price = self.validators.derive_reference_gas_price();
-    // Because of precision issues with integer divisions, we expect that there will be some
-    // remaining balance in `total_validator_rewards`.
-    let leftover_staking_rewards = total_validator_rewards;
-    // Burn any remaining leftover rewards.
-    burnt_tokens_amount = burnt_tokens_amount + leftover_staking_rewards.value();
-    self.iota_treasury_cap.burn_balance(leftover_staking_rewards, ctx);
-
-    let refunded_storage_rebate =
-        self.storage_fund.advance_epoch(
-            storage_charge,
-            storage_rebate_amount,
-            non_refundable_storage_fee_amount,
-        );
-
-    event::emit(
-        SystemEpochInfoEvent \{
-            epoch: self.epoch,
-            protocol_version: self.protocol_version,
-            reference_gas_price: self.reference_gas_price,
-            total_stake: new_total_stake,
-            storage_charge: storage_charge_value,
-            storage_rebate: storage_rebate_amount,
-            storage_fund_balance: self.storage_fund.total_balance(),
-            total_gas_fees: computation_charge,
-            total_stake_rewards_distributed: total_validator_rewards_distributed,
-            burnt_tokens_amount,
-            minted_tokens_amount
-        }
-    );
-    self.safe_mode = false;
-    // Double check that the gas from safe mode has been processed.
-    assert!(self.safe_mode_storage_rebates == 0
-        && self.safe_mode_storage_charges.value() == 0
-        && self.safe_mode_computation_rewards.value() == 0, ESafeModeGasNotProcessed);
-
-    // Return the storage rebate split from storage fund that's already refunded to the transaction senders.
-    // This will be burnt at the last step of epoch change programmable transaction.
-    refunded_storage_rebate
-}
-
- - - -
- - - -## Function `match_computation_reward_to_target_reward` - -Mint or burn IOTA tokens depending on the given target reward per validator -and the amount of computation fees burned in this epoch. - - -

-fun match_computation_reward_to_target_reward(validator_target_reward: u64, computation_reward: balance::Balance<iota::IOTA>, iota_treasury_cap: &mut iota::IotaTreasuryCap, ctx: &tx_context::TxContext): (balance::Balance<iota::IOTA>, u64, u64)
-
- - - -
-Implementation - - -

-fun match_computation_reward_to_target_reward(
-    validator_target_reward: u64,
-    mut computation_reward: Balance<IOTA>,
-    iota_treasury_cap: &mut iota::iota::IotaTreasuryCap,
-    ctx: &TxContext,
-): (Balance<IOTA>, u64, u64) \{
-    let mut burnt_tokens_amount = 0;
-    let mut minted_tokens_amount = 0;
-    if (computation_reward.value() < validator_target_reward) \{
-        let tokens_to_mint = validator_target_reward - computation_reward.value();
-        let new_tokens = iota_treasury_cap.mint_balance(tokens_to_mint, ctx);
-        minted_tokens_amount = new_tokens.value();
-        computation_reward.join(new_tokens);
-    } else if (computation_reward.value() > validator_target_reward) \{
-        let tokens_to_burn = computation_reward.value() - validator_target_reward;
-        let rewards_to_burn = computation_reward.split(tokens_to_burn);
-        burnt_tokens_amount = rewards_to_burn.value();
-        iota_treasury_cap.burn_balance(rewards_to_burn, ctx);
-    };
-    (computation_reward, minted_tokens_amount, burnt_tokens_amount)
-}
-
- - - -
- - - -## Function `epoch` - -Return the current epoch number. Useful for applications that need a coarse-grained concept of time, -since epochs are ever-increasing and epoch changes are intended to happen every 24 hours. - - -

-public(friend) fun epoch(self: &iota_system_state_inner::IotaSystemStateInnerV2): u64
-
- - - -
-Implementation - - -

-public(package) fun epoch(self: &IotaSystemStateInnerV2): u64 \{
-    self.epoch
-}
-
- - - -
- - - -## Function `protocol_version` - - - -

-public(friend) fun protocol_version(self: &iota_system_state_inner::IotaSystemStateInnerV2): u64
-
- - - -
-Implementation - - -

-public(package) fun protocol_version(self: &IotaSystemStateInnerV2): u64 \{
-    self.protocol_version
-}
-
- - - -
- - - -## Function `system_state_version` - - - -

-public(friend) fun system_state_version(self: &iota_system_state_inner::IotaSystemStateInnerV2): u64
-
- - - -
-Implementation - - -

-public(package) fun system_state_version(self: &IotaSystemStateInnerV2): u64 \{
-    self.system_state_version
-}
-
- - - -
- - - -## Function `genesis_system_state_version` - -This function always return the genesis system state version, which is used to create the system state in genesis. -It should never change for a given network. - - -

-public(friend) fun genesis_system_state_version(): u64
-
- - - -
-Implementation - - -

-public(package) fun genesis_system_state_version(): u64 \{
-    SYSTEM_STATE_VERSION_V1
-}
-
- - - -
- - - -## Function `epoch_start_timestamp_ms` - -Returns unix timestamp of the start of current epoch - - -

-public(friend) fun epoch_start_timestamp_ms(self: &iota_system_state_inner::IotaSystemStateInnerV2): u64
-
- - - -
-Implementation - - -

-public(package) fun epoch_start_timestamp_ms(self: &IotaSystemStateInnerV2): u64 \{
-    self.epoch_start_timestamp_ms
-}
-
- - - -
- - - -## Function `validator_stake_amount` - -Returns the total amount staked with -validator_addr. -Aborts if -validator_addr is not an active validator. - - -

-public(friend) fun validator_stake_amount(self: &iota_system_state_inner::IotaSystemStateInnerV2, validator_addr: address): u64
-
- - - -
-Implementation - - -

-public(package) fun validator_stake_amount(self: &IotaSystemStateInnerV2, validator_addr: address): u64 \{
-    self.validators.validator_total_stake_amount(validator_addr)
-}
-
- - - -
- - - -## Function `validator_staking_pool_id` - -Returns the staking pool id of a given validator. -Aborts if -validator_addr is not an active validator. - - -

-public(friend) fun validator_staking_pool_id(self: &iota_system_state_inner::IotaSystemStateInnerV2, validator_addr: address): object::ID
-
- - - -
-Implementation - - -

-public(package) fun validator_staking_pool_id(self: &IotaSystemStateInnerV2, validator_addr: address): ID \{
-
-    self.validators.validator_staking_pool_id(validator_addr)
-}
-
- - - -
- - - -## Function `validator_staking_pool_mappings` - -Returns reference to the staking pool mappings that map pool ids to active validator addresses - - -

-public(friend) fun validator_staking_pool_mappings(self: &iota_system_state_inner::IotaSystemStateInnerV2): &table::Table<object::ID, address>
-
- - - -
-Implementation - - -

-public(package) fun validator_staking_pool_mappings(self: &IotaSystemStateInnerV2): &Table<ID, address> \{
-
-    self.validators.staking_pool_mappings()
-}
-
- - - -
- - - -## Function `get_total_iota_supply` - -Returns the total iota supply. - - -

-public(friend) fun get_total_iota_supply(self: &iota_system_state_inner::IotaSystemStateInnerV2): u64
-
- - - -
-Implementation - - -

-public(package) fun get_total_iota_supply(self: &IotaSystemStateInnerV2): u64 \{
-    self.iota_treasury_cap.total_supply()
-}
-
- - - -
- - - -## Function `get_reporters_of` - -Returns all the validators who are currently reporting -addr - - -

-public(friend) fun get_reporters_of(self: &iota_system_state_inner::IotaSystemStateInnerV2, addr: address): vec_set::VecSet<address>
-
- - - -
-Implementation - - -

-public(package) fun get_reporters_of(self: &IotaSystemStateInnerV2, addr: address): VecSet<address> \{
-
-    if (self.validator_report_records.contains(&addr)) \{
-        self.validator_report_records[&addr]
-    } else \{
-        vec_set::empty()
-    }
-}
-
- - - -
- - - -## Function `get_storage_fund_total_balance` - - - -

-public(friend) fun get_storage_fund_total_balance(self: &iota_system_state_inner::IotaSystemStateInnerV2): u64
-
- - - -
-Implementation - - -

-public(package) fun get_storage_fund_total_balance(self: &IotaSystemStateInnerV2): u64 \{
-    self.storage_fund.total_balance()
-}
-
- - - -
- - - -## Function `get_storage_fund_object_rebates` - - - -

-public(friend) fun get_storage_fund_object_rebates(self: &iota_system_state_inner::IotaSystemStateInnerV2): u64
-
- - - -
-Implementation - - -

-public(package) fun get_storage_fund_object_rebates(self: &IotaSystemStateInnerV2): u64 \{
-    self.storage_fund.total_object_storage_rebates()
-}
-
- - - -
- - - -## Function `pool_exchange_rates` - - - -

-public(friend) fun pool_exchange_rates(self: &mut iota_system_state_inner::IotaSystemStateInnerV2, pool_id: &object::ID): &table::Table<u64, staking_pool::PoolTokenExchangeRate>
-
- - - -
-Implementation - - -

-public(package) fun pool_exchange_rates(
-    self: &mut IotaSystemStateInnerV2,
-    pool_id: &ID
-): &Table<u64, PoolTokenExchangeRate>  \{
-    let validators = &mut self.validators;
-    validators.pool_exchange_rates(pool_id)
-}
-
- - - -
- - - -## Function `active_validator_addresses` - - - -

-public(friend) fun active_validator_addresses(self: &iota_system_state_inner::IotaSystemStateInnerV2): vector<address>
-
- - - -
-Implementation - - -

-public(package) fun active_validator_addresses(self: &IotaSystemStateInnerV2): vector<address> \{
-    let validator_set = &self.validators;
-    validator_set.active_validator_addresses()
-}
-
- - - -
- - - -## Function `extract_coin_balance` - -Extract required Balance from vector of `Coin`, transfer the remainder back to sender. - - -

-fun extract_coin_balance(coins: vector<coin::Coin<iota::IOTA>>, amount: option::Option<u64>, ctx: &mut tx_context::TxContext): balance::Balance<iota::IOTA>
-
- - - -
-Implementation - - -

-fun extract_coin_balance(mut coins: vector<Coin<IOTA>>, amount: option::Option<u64>, ctx: &mut TxContext): Balance<IOTA> \{
-    let mut merged_coin = coins.pop_back();
-    merged_coin.join_vec(coins);
-
-    let mut total_balance = merged_coin.into_balance();
-    // return the full amount if amount is not specified
-    if (amount.is_some()) \{
-        let amount = amount.destroy_some();
-        let balance = total_balance.split(amount);
-        // transfer back the remainder if non zero.
-        if (total_balance.value() > 0) \{
-            transfer::public_transfer(total_balance.into_coin(ctx), ctx.sender());
-        } else \{
-            total_balance.destroy_zero();
-        };
-        balance
-    } else \{
-        total_balance
-    }
-}
-
- - - -
diff --git a/crates/iota-framework/docs/iota-system/staking_pool.mdx b/crates/iota-framework/docs/iota-system/staking_pool.mdx deleted file mode 100644 index 8ed1bc8c57e..00000000000 --- a/crates/iota-framework/docs/iota-system/staking_pool.mdx +++ /dev/null @@ -1,1539 +0,0 @@ ---- -title: Module `0x3::staking_pool` ---- -import Link from '@docusaurus/Link'; - - - - -- [Resource `StakingPool`](#0x3_staking_pool_StakingPool) -- [Struct `PoolTokenExchangeRate`](#0x3_staking_pool_PoolTokenExchangeRate) -- [Resource `StakedIota`](#0x3_staking_pool_StakedIota) -- [Constants](#@Constants_0) -- [Function `new`](#0x3_staking_pool_new) -- [Function `request_add_stake`](#0x3_staking_pool_request_add_stake) -- [Function `request_withdraw_stake`](#0x3_staking_pool_request_withdraw_stake) -- [Function `withdraw_from_principal`](#0x3_staking_pool_withdraw_from_principal) -- [Function `unwrap_staked_iota`](#0x3_staking_pool_unwrap_staked_iota) -- [Function `deposit_rewards`](#0x3_staking_pool_deposit_rewards) -- [Function `process_pending_stakes_and_withdraws`](#0x3_staking_pool_process_pending_stakes_and_withdraws) -- [Function `process_pending_stake_withdraw`](#0x3_staking_pool_process_pending_stake_withdraw) -- [Function `process_pending_stake`](#0x3_staking_pool_process_pending_stake) -- [Function `withdraw_rewards`](#0x3_staking_pool_withdraw_rewards) -- [Function `activate_staking_pool`](#0x3_staking_pool_activate_staking_pool) -- [Function `deactivate_staking_pool`](#0x3_staking_pool_deactivate_staking_pool) -- [Function `iota_balance`](#0x3_staking_pool_iota_balance) -- [Function `pool_id`](#0x3_staking_pool_pool_id) -- [Function `staked_iota_amount`](#0x3_staking_pool_staked_iota_amount) -- [Function `stake_activation_epoch`](#0x3_staking_pool_stake_activation_epoch) -- [Function `is_preactive`](#0x3_staking_pool_is_preactive) -- [Function `is_inactive`](#0x3_staking_pool_is_inactive) -- [Function `split`](#0x3_staking_pool_split) -- [Function `split_staked_iota`](#0x3_staking_pool_split_staked_iota) -- [Function `join_staked_iota`](#0x3_staking_pool_join_staked_iota) -- [Function `is_equal_staking_metadata`](#0x3_staking_pool_is_equal_staking_metadata) -- [Function `pool_token_exchange_rate_at_epoch`](#0x3_staking_pool_pool_token_exchange_rate_at_epoch) -- [Function `pending_stake_amount`](#0x3_staking_pool_pending_stake_amount) -- [Function `pending_stake_withdraw_amount`](#0x3_staking_pool_pending_stake_withdraw_amount) -- [Function `exchange_rates`](#0x3_staking_pool_exchange_rates) -- [Function `iota_amount`](#0x3_staking_pool_iota_amount) -- [Function `pool_token_amount`](#0x3_staking_pool_pool_token_amount) -- [Function `is_preactive_at_epoch`](#0x3_staking_pool_is_preactive_at_epoch) -- [Function `get_iota_amount`](#0x3_staking_pool_get_iota_amount) -- [Function `get_token_amount`](#0x3_staking_pool_get_token_amount) -- [Function `initial_exchange_rate`](#0x3_staking_pool_initial_exchange_rate) -- [Function `check_balance_invariants`](#0x3_staking_pool_check_balance_invariants) - - -

-use 0x1::option;
-use 0x2::bag;
-use 0x2::balance;
-use 0x2::iota;
-use 0x2::math;
-use 0x2::object;
-use 0x2::table;
-use 0x2::transfer;
-use 0x2::tx_context;
-
- - - - - -## Resource `StakingPool` - -A staking pool embedded in each validator struct in the system state object. - - -

-struct StakingPool has store, key
-
- - - -
-Fields - - -
-
- -id: object::UID -
-
- -
-
- -activation_epoch: option::Option<u64> -
-
- The epoch at which this pool became active. - The value is -None if the pool is pre-active and -Some(<epoch_number>) if active or inactive. -
-
- -deactivation_epoch: option::Option<u64> -
-
- The epoch at which this staking pool ceased to be active. -None = \{pre-active, active}, - -Some(<epoch_number>) if in-active, and it was de-activated at epoch -<epoch_number>. -
-
- -iota_balance: u64 -
-
- The total number of IOTA tokens in this pool, including the IOTA in the rewards_pool, as well as in all the principal - in the -StakedIota object, updated at epoch boundaries. -
-
- -rewards_pool: balance::Balance<iota::IOTA> -
-
- The epoch stake rewards will be added here at the end of each epoch. -
-
- -pool_token_balance: u64 -
-
- Total number of pool tokens issued by the pool. -
-
- -exchange_rates: table::Table<u64, staking_pool::PoolTokenExchangeRate> -
-
- Exchange rate history of previous epochs. Key is the epoch number. - The entries start from the -activation_epoch of this pool and contains exchange rates at the beginning of each epoch, - i.e., right after the rewards for the previous epoch have been deposited into the pool. -
-
- -pending_stake: u64 -
-
- Pending stake amount for this epoch, emptied at epoch boundaries. -
-
- -pending_total_iota_withdraw: u64 -
-
- Pending stake withdrawn during the current epoch, emptied at epoch boundaries. - This includes both the principal and rewards IOTA withdrawn. -
-
- -pending_pool_token_withdraw: u64 -
-
- Pending pool token withdrawn during the current epoch, emptied at epoch boundaries. -
-
- -extra_fields: bag::Bag -
-
- Any extra fields that's not defined statically. -
-
- - -
- - - -## Struct `PoolTokenExchangeRate` - -Struct representing the exchange rate of the stake pool token to IOTA. - - -

-struct PoolTokenExchangeRate has copy, drop, store
-
- - - -
-Fields - - -
-
- -iota_amount: u64 -
-
- -
-
- -pool_token_amount: u64 -
-
- -
-
- - -
- - - -## Resource `StakedIota` - -A self-custodial object holding the staked IOTA tokens. - - -

-struct StakedIota has store, key
-
- - - -
-Fields - - -
-
- -id: object::UID -
-
- -
-
- -pool_id: object::ID -
-
- ID of the staking pool we are staking with. -
-
- -stake_activation_epoch: u64 -
-
- The epoch at which the stake becomes active. -
-
- -principal: balance::Balance<iota::IOTA> -
-
- The staked IOTA tokens. -
-
- - -
- - - -## Constants - - - - - - -

-const EActivationOfInactivePool: u64 = 16;
-
- - - - - - - -

-const EDeactivationOfInactivePool: u64 = 11;
-
- - - - - - - -

-const EDelegationOfZeroIota: u64 = 17;
-
- - - - - - - -

-const EDelegationToInactivePool: u64 = 10;
-
- - - - - - - -

-const EDestroyNonzeroBalance: u64 = 5;
-
- - - - - - - -

-const EIncompatibleStakedIota: u64 = 12;
-
- - - - - - - -

-const EInsufficientIotaTokenBalance: u64 = 3;
-
- - - - - - - -

-const EInsufficientPoolTokenBalance: u64 = 0;
-
- - - - - - - -

-const EInsufficientRewardsPoolBalance: u64 = 4;
-
- - - - - - - -

-const EPendingDelegationDoesNotExist: u64 = 8;
-
- - - - - - - -

-const EPoolAlreadyActive: u64 = 14;
-
- - - - - - - -

-const EPoolNotPreactive: u64 = 15;
-
- - - - - - - -

-const EStakedIotaBelowThreshold: u64 = 18;
-
- - - - - - - -

-const ETokenBalancesDoNotMatchExchangeRate: u64 = 9;
-
- - - - - - - -

-const ETokenTimeLockIsSome: u64 = 6;
-
- - - - - - - -

-const EWithdrawAmountCannotBeZero: u64 = 2;
-
- - - - - - - -

-const EWithdrawalInSameEpoch: u64 = 13;
-
- - - - - - - -

-const EWrongDelegation: u64 = 7;
-
- - - - - - - -

-const EWrongPool: u64 = 1;
-
- - - - - -StakedIota objects cannot be split to below this amount. - - -

-const MIN_STAKING_THRESHOLD: u64 = 1000000000;
-
- - - - - -## Function `new` - -Create a new, empty staking pool. - - -

-public(friend) fun new(ctx: &mut tx_context::TxContext): staking_pool::StakingPool
-
- - - -
-Implementation - - -

-public(package) fun new(ctx: &mut TxContext) : StakingPool \{
-    let exchange_rates = table::new(ctx);
-    StakingPool \{
-        id: object::new(ctx),
-        activation_epoch: option::none(),
-        deactivation_epoch: option::none(),
-        iota_balance: 0,
-        rewards_pool: balance::zero(),
-        pool_token_balance: 0,
-        exchange_rates,
-        pending_stake: 0,
-        pending_total_iota_withdraw: 0,
-        pending_pool_token_withdraw: 0,
-        extra_fields: bag::new(ctx),
-    }
-}
-
- - - -
- - - -## Function `request_add_stake` - -Request to stake to a staking pool. The stake starts counting at the beginning of the next epoch, - - -

-public(friend) fun request_add_stake(pool: &mut staking_pool::StakingPool, stake: balance::Balance<iota::IOTA>, stake_activation_epoch: u64, ctx: &mut tx_context::TxContext): staking_pool::StakedIota
-
- - - -
-Implementation - - -

-public(package) fun request_add_stake(
-    pool: &mut StakingPool,
-    stake: Balance<IOTA>,
-    stake_activation_epoch: u64,
-    ctx: &mut TxContext
-) : StakedIota \{
-    let iota_amount = stake.value();
-    assert!(!is_inactive(pool), EDelegationToInactivePool);
-    assert!(iota_amount > 0, EDelegationOfZeroIota);
-    let staked_iota = StakedIota \{
-        id: object::new(ctx),
-        pool_id: object::id(pool),
-        stake_activation_epoch,
-        principal: stake,
-    };
-    pool.pending_stake = pool.pending_stake + iota_amount;
-    staked_iota
-}
-
- - - -
- - - -## Function `request_withdraw_stake` - -Request to withdraw the given stake plus rewards from a staking pool. -Both the principal and corresponding rewards in IOTA are withdrawn. -A proportional amount of pool token withdraw is recorded and processed at epoch change time. - - -

-public(friend) fun request_withdraw_stake(pool: &mut staking_pool::StakingPool, staked_iota: staking_pool::StakedIota, ctx: &tx_context::TxContext): balance::Balance<iota::IOTA>
-
- - - -
-Implementation - - -

-public(package) fun request_withdraw_stake(
-    pool: &mut StakingPool,
-    staked_iota: StakedIota,
-    ctx: &TxContext
-) : Balance<IOTA> \{
-    let (pool_token_withdraw_amount, mut principal_withdraw) =
-        withdraw_from_principal(pool, staked_iota);
-    let principal_withdraw_amount = principal_withdraw.value();
-
-    let rewards_withdraw = withdraw_rewards(
-        pool, principal_withdraw_amount, pool_token_withdraw_amount, ctx.epoch()
-    );
-    let total_iota_withdraw_amount = principal_withdraw_amount + rewards_withdraw.value();
-
-    pool.pending_total_iota_withdraw = pool.pending_total_iota_withdraw + total_iota_withdraw_amount;
-    pool.pending_pool_token_withdraw = pool.pending_pool_token_withdraw + pool_token_withdraw_amount;
-
-    // If the pool is inactive, we immediately process the withdrawal.
-    if (is_inactive(pool)) process_pending_stake_withdraw(pool);
-
-    // TODO: implement withdraw bonding period here.
-    principal_withdraw.join(rewards_withdraw);
-    principal_withdraw
-}
-
- - - -
- - - -## Function `withdraw_from_principal` - -Withdraw the principal IOTA stored in the StakedIota object, and calculate the corresponding amount of pool -tokens using exchange rate at staking epoch. -Returns values are amount of pool tokens withdrawn and withdrawn principal portion of IOTA. - - -

-public(friend) fun withdraw_from_principal(pool: &staking_pool::StakingPool, staked_iota: staking_pool::StakedIota): (u64, balance::Balance<iota::IOTA>)
-
- - - -
-Implementation - - -

-public(package) fun withdraw_from_principal(
-    pool: &StakingPool,
-    staked_iota: StakedIota,
-) : (u64, Balance<IOTA>) \{
-
-    // Check that the stake information matches the pool.
-    assert!(staked_iota.pool_id == object::id(pool), EWrongPool);
-
-    let exchange_rate_at_staking_epoch = pool_token_exchange_rate_at_epoch(pool, staked_iota.stake_activation_epoch);
-    let principal_withdraw = unwrap_staked_iota(staked_iota);
-    let pool_token_withdraw_amount = get_token_amount(
-		&exchange_rate_at_staking_epoch,
-		principal_withdraw.value()
-	);
-
-    (
-        pool_token_withdraw_amount,
-        principal_withdraw,
-    )
-}
-
- - - -
- - - -## Function `unwrap_staked_iota` - - - -

-fun unwrap_staked_iota(staked_iota: staking_pool::StakedIota): balance::Balance<iota::IOTA>
-
- - - -
-Implementation - - -

-fun unwrap_staked_iota(staked_iota: StakedIota): Balance<IOTA> \{
-    let StakedIota \{
-        id,
-        pool_id: _,
-        stake_activation_epoch: _,
-        principal,
-    } = staked_iota;
-    object::delete(id);
-    principal
-}
-
- - - -
- - - -## Function `deposit_rewards` - -Called at epoch advancement times to add rewards (in IOTA) to the staking pool. - - -

-public(friend) fun deposit_rewards(pool: &mut staking_pool::StakingPool, rewards: balance::Balance<iota::IOTA>)
-
- - - -
-Implementation - - -

-public(package) fun deposit_rewards(pool: &mut StakingPool, rewards: Balance<IOTA>) \{
-    pool.iota_balance = pool.iota_balance + rewards.value();
-    pool.rewards_pool.join(rewards);
-}
-
- - - -
- - - -## Function `process_pending_stakes_and_withdraws` - - - -

-public(friend) fun process_pending_stakes_and_withdraws(pool: &mut staking_pool::StakingPool, ctx: &tx_context::TxContext)
-
- - - -
-Implementation - - -

-public(package) fun process_pending_stakes_and_withdraws(pool: &mut StakingPool, ctx: &TxContext) \{
-    let new_epoch = ctx.epoch() + 1;
-    process_pending_stake_withdraw(pool);
-    process_pending_stake(pool);
-    pool.exchange_rates.add(
-        new_epoch,
-        PoolTokenExchangeRate \{ iota_amount: pool.iota_balance, pool_token_amount: pool.pool_token_balance },
-    );
-    check_balance_invariants(pool, new_epoch);
-}
-
- - - -
- - - -## Function `process_pending_stake_withdraw` - -Called at epoch boundaries to process pending stake withdraws requested during the epoch. -Also called immediately upon withdrawal if the pool is inactive. - - -

-fun process_pending_stake_withdraw(pool: &mut staking_pool::StakingPool)
-
- - - -
-Implementation - - -

-fun process_pending_stake_withdraw(pool: &mut StakingPool) \{
-    pool.iota_balance = pool.iota_balance - pool.pending_total_iota_withdraw;
-    pool.pool_token_balance = pool.pool_token_balance - pool.pending_pool_token_withdraw;
-    pool.pending_total_iota_withdraw = 0;
-    pool.pending_pool_token_withdraw = 0;
-}
-
- - - -
- - - -## Function `process_pending_stake` - -Called at epoch boundaries to process the pending stake. - - -

-public(friend) fun process_pending_stake(pool: &mut staking_pool::StakingPool)
-
- - - -
-Implementation - - -

-public(package) fun process_pending_stake(pool: &mut StakingPool) \{
-    // Use the most up to date exchange rate with the rewards deposited and withdraws effectuated.
-    let latest_exchange_rate =
-        PoolTokenExchangeRate \{ iota_amount: pool.iota_balance, pool_token_amount: pool.pool_token_balance };
-    pool.iota_balance = pool.iota_balance + pool.pending_stake;
-    pool.pool_token_balance = get_token_amount(&latest_exchange_rate, pool.iota_balance);
-    pool.pending_stake = 0;
-}
-
- - - -
- - - -## Function `withdraw_rewards` - -This function does the following: -1. Calculates the total amount of IOTA (including principal and rewards) that the provided pool tokens represent -at the current exchange rate. -2. Using the above number and the given -principal_withdraw_amount, calculates the rewards portion of the -stake we should withdraw. -3. Withdraws the rewards portion from the rewards pool at the current exchange rate. We only withdraw the rewards -portion because the principal portion was already taken out of the staker's self custodied StakedIota. - - -

-fun withdraw_rewards(pool: &mut staking_pool::StakingPool, principal_withdraw_amount: u64, pool_token_withdraw_amount: u64, epoch: u64): balance::Balance<iota::IOTA>
-
- - - -
-Implementation - - -

-fun withdraw_rewards(
-    pool: &mut StakingPool,
-    principal_withdraw_amount: u64,
-    pool_token_withdraw_amount: u64,
-    epoch: u64,
-) : Balance<IOTA> \{
-    let exchange_rate = pool_token_exchange_rate_at_epoch(pool, epoch);
-    let total_iota_withdraw_amount = get_iota_amount(&exchange_rate, pool_token_withdraw_amount);
-    let mut reward_withdraw_amount =
-        if (total_iota_withdraw_amount >= principal_withdraw_amount)
-            total_iota_withdraw_amount - principal_withdraw_amount
-        else 0;
-    // This may happen when we are withdrawing everything from the pool and
-    // the rewards pool balance may be less than reward_withdraw_amount.
-    // TODO: FIGURE OUT EXACTLY WHY THIS CAN HAPPEN.
-    reward_withdraw_amount = math::min(reward_withdraw_amount, pool.rewards_pool.value());
-    pool.rewards_pool.split(reward_withdraw_amount)
-}
-
- - - -
- - - -## Function `activate_staking_pool` - -Called by -validator module to activate a staking pool. - - -

-public(friend) fun activate_staking_pool(pool: &mut staking_pool::StakingPool, activation_epoch: u64)
-
- - - -
-Implementation - - -

-public(package) fun activate_staking_pool(pool: &mut StakingPool, activation_epoch: u64) \{
-    // Add the initial exchange rate to the table.
-    pool.exchange_rates.add(
-        activation_epoch,
-        initial_exchange_rate()
-    );
-    // Check that the pool is preactive and not inactive.
-    assert!(is_preactive(pool), EPoolAlreadyActive);
-    assert!(!is_inactive(pool), EActivationOfInactivePool);
-    // Fill in the active epoch.
-    pool.activation_epoch.fill(activation_epoch);
-}
-
- - - -
- - - -## Function `deactivate_staking_pool` - -Deactivate a staking pool by setting the -deactivation_epoch. After -this pool deactivation, the pool stops earning rewards. Only stake -withdraws can be made to the pool. - - -

-public(friend) fun deactivate_staking_pool(pool: &mut staking_pool::StakingPool, deactivation_epoch: u64)
-
- - - -
-Implementation - - -

-public(package) fun deactivate_staking_pool(pool: &mut StakingPool, deactivation_epoch: u64) \{
-    // We can't deactivate an already deactivated pool.
-    assert!(!is_inactive(pool), EDeactivationOfInactivePool);
-    pool.deactivation_epoch = option::some(deactivation_epoch);
-}
-
- - - -
- - - -## Function `iota_balance` - - - -

-public fun iota_balance(pool: &staking_pool::StakingPool): u64
-
- - - -
-Implementation - - -

-public fun iota_balance(pool: &StakingPool): u64 \{ pool.iota_balance }
-
- - - -
- - - -## Function `pool_id` - - - -

-public fun pool_id(staked_iota: &staking_pool::StakedIota): object::ID
-
- - - -
-Implementation - - -

-public fun pool_id(staked_iota: &StakedIota): ID \{ staked_iota.pool_id }
-
- - - -
- - - -## Function `staked_iota_amount` - - - -

-public fun staked_iota_amount(staked_iota: &staking_pool::StakedIota): u64
-
- - - -
-Implementation - - -

-public fun staked_iota_amount(staked_iota: &StakedIota): u64 \{ staked_iota.principal.value() }
-
- - - -
- - - -## Function `stake_activation_epoch` - - - -

-public fun stake_activation_epoch(staked_iota: &staking_pool::StakedIota): u64
-
- - - -
-Implementation - - -

-public fun stake_activation_epoch(staked_iota: &StakedIota): u64 \{
-    staked_iota.stake_activation_epoch
-}
-
- - - -
- - - -## Function `is_preactive` - -Returns true if the input staking pool is preactive. - - -

-public fun is_preactive(pool: &staking_pool::StakingPool): bool
-
- - - -
-Implementation - - -

-public fun is_preactive(pool: &StakingPool): bool\{
-    pool.activation_epoch.is_none()
-}
-
- - - -
- - - -## Function `is_inactive` - -Returns true if the input staking pool is inactive. - - -

-public fun is_inactive(pool: &staking_pool::StakingPool): bool
-
- - - -
-Implementation - - -

-public fun is_inactive(pool: &StakingPool): bool \{
-    pool.deactivation_epoch.is_some()
-}
-
- - - -
- - - -## Function `split` - -Split StakedIota -self to two parts, one with principal -split_amount, -and the remaining principal is left in -self. -All the other parameters of the StakedIota like -stake_activation_epoch or -pool_id remain the same. - - -

-public fun split(self: &mut staking_pool::StakedIota, split_amount: u64, ctx: &mut tx_context::TxContext): staking_pool::StakedIota
-
- - - -
-Implementation - - -

-public fun split(self: &mut StakedIota, split_amount: u64, ctx: &mut TxContext): StakedIota \{
-    let original_amount = self.principal.value();
-    assert!(split_amount <= original_amount, EInsufficientIotaTokenBalance);
-    let remaining_amount = original_amount - split_amount;
-    // Both resulting parts should have at least MIN_STAKING_THRESHOLD.
-    assert!(remaining_amount >= MIN_STAKING_THRESHOLD, EStakedIotaBelowThreshold);
-    assert!(split_amount >= MIN_STAKING_THRESHOLD, EStakedIotaBelowThreshold);
-    StakedIota \{
-        id: object::new(ctx),
-        pool_id: self.pool_id,
-        stake_activation_epoch: self.stake_activation_epoch,
-        principal: self.principal.split(split_amount),
-    }
-}
-
- - - -
- - - -## Function `split_staked_iota` - -Split the given StakedIota to the two parts, one with principal -split_amount, -transfer the newly split part to the sender address. - - -

-public entry fun split_staked_iota(stake: &mut staking_pool::StakedIota, split_amount: u64, ctx: &mut tx_context::TxContext)
-
- - - -
-Implementation - - -

-public entry fun split_staked_iota(stake: &mut StakedIota, split_amount: u64, ctx: &mut TxContext) \{
-    transfer::transfer(split(stake, split_amount, ctx), ctx.sender());
-}
-
- - - -
- - - -## Function `join_staked_iota` - -Consume the staked iota -other and add its value to -self. -Aborts if some of the staking parameters are incompatible (pool id, stake activation epoch, etc.) - - -

-public entry fun join_staked_iota(self: &mut staking_pool::StakedIota, other: staking_pool::StakedIota)
-
- - - -
-Implementation - - -

-public entry fun join_staked_iota(self: &mut StakedIota, other: StakedIota) \{
-    assert!(is_equal_staking_metadata(self, &other), EIncompatibleStakedIota);
-    let StakedIota \{
-        id,
-        pool_id: _,
-        stake_activation_epoch: _,
-        principal,
-    } = other;
-
-    id.delete();
-    self.principal.join(principal);
-}
-
- - - -
- - - -## Function `is_equal_staking_metadata` - -Returns true if all the staking parameters of the staked iota except the principal are identical - - -

-public fun is_equal_staking_metadata(self: &staking_pool::StakedIota, other: &staking_pool::StakedIota): bool
-
- - - -
-Implementation - - -

-public fun is_equal_staking_metadata(self: &StakedIota, other: &StakedIota): bool \{
-    (self.pool_id == other.pool_id) &&
-    (self.stake_activation_epoch == other.stake_activation_epoch)
-}
-
- - - -
- - - -## Function `pool_token_exchange_rate_at_epoch` - - - -

-public fun pool_token_exchange_rate_at_epoch(pool: &staking_pool::StakingPool, epoch: u64): staking_pool::PoolTokenExchangeRate
-
- - - -
-Implementation - - -

-public fun pool_token_exchange_rate_at_epoch(pool: &StakingPool, epoch: u64): PoolTokenExchangeRate \{
-    // If the pool is preactive then the exchange rate is always 1:1.
-    if (is_preactive_at_epoch(pool, epoch)) \{
-        return initial_exchange_rate()
-    };
-    let clamped_epoch = pool.deactivation_epoch.get_with_default(epoch);
-    let mut epoch = math::min(clamped_epoch, epoch);
-    let activation_epoch = *pool.activation_epoch.borrow();
-
-    // Find the latest epoch that's earlier than the given epoch with an entry in the table
-    while (epoch >= activation_epoch) \{
-        if (pool.exchange_rates.contains(epoch)) \{
-            return pool.exchange_rates[epoch]
-        };
-        epoch = epoch - 1;
-    };
-    // This line really should be unreachable. Do we want an assert false here?
-    initial_exchange_rate()
-}
-
- - - -
- - - -## Function `pending_stake_amount` - -Returns the total value of the pending staking requests for this staking pool. - - -

-public fun pending_stake_amount(staking_pool: &staking_pool::StakingPool): u64
-
- - - -
-Implementation - - -

-public fun pending_stake_amount(staking_pool: &StakingPool): u64 \{
-    staking_pool.pending_stake
-}
-
- - - -
- - - -## Function `pending_stake_withdraw_amount` - -Returns the total withdrawal from the staking pool this epoch. - - -

-public fun pending_stake_withdraw_amount(staking_pool: &staking_pool::StakingPool): u64
-
- - - -
-Implementation - - -

-public fun pending_stake_withdraw_amount(staking_pool: &StakingPool): u64 \{
-    staking_pool.pending_total_iota_withdraw
-}
-
- - - -
- - - -## Function `exchange_rates` - - - -

-public(friend) fun exchange_rates(pool: &staking_pool::StakingPool): &table::Table<u64, staking_pool::PoolTokenExchangeRate>
-
- - - -
-Implementation - - -

-public(package) fun exchange_rates(pool: &StakingPool): &Table<u64, PoolTokenExchangeRate> \{
-    &pool.exchange_rates
-}
-
- - - -
- - - -## Function `iota_amount` - - - -

-public fun iota_amount(exchange_rate: &staking_pool::PoolTokenExchangeRate): u64
-
- - - -
-Implementation - - -

-public fun iota_amount(exchange_rate: &PoolTokenExchangeRate): u64 \{
-    exchange_rate.iota_amount
-}
-
- - - -
- - - -## Function `pool_token_amount` - - - -

-public fun pool_token_amount(exchange_rate: &staking_pool::PoolTokenExchangeRate): u64
-
- - - -
-Implementation - - -

-public fun pool_token_amount(exchange_rate: &PoolTokenExchangeRate): u64 \{
-    exchange_rate.pool_token_amount
-}
-
- - - -
- - - -## Function `is_preactive_at_epoch` - -Returns true if the provided staking pool is preactive at the provided epoch. - - -

-fun is_preactive_at_epoch(pool: &staking_pool::StakingPool, epoch: u64): bool
-
- - - -
-Implementation - - -

-fun is_preactive_at_epoch(pool: &StakingPool, epoch: u64): bool\{
-    // Either the pool is currently preactive or the pool's starting epoch is later than the provided epoch.
-    is_preactive(pool) || (*pool.activation_epoch.borrow() > epoch)
-}
-
- - - -
- - - -## Function `get_iota_amount` - - - -

-fun get_iota_amount(exchange_rate: &staking_pool::PoolTokenExchangeRate, token_amount: u64): u64
-
- - - -
-Implementation - - -

-fun get_iota_amount(exchange_rate: &PoolTokenExchangeRate, token_amount: u64): u64 \{
-    // When either amount is 0, that means we have no stakes with this pool.
-    // The other amount might be non-zero when there's dust left in the pool.
-    if (exchange_rate.iota_amount == 0 || exchange_rate.pool_token_amount == 0) \{
-        return token_amount
-    };
-    let res = exchange_rate.iota_amount as u128
-            * (token_amount as u128)
-            / (exchange_rate.pool_token_amount as u128);
-    res as u64
-}
-
- - - -
- - - -## Function `get_token_amount` - - - -

-fun get_token_amount(exchange_rate: &staking_pool::PoolTokenExchangeRate, iota_amount: u64): u64
-
- - - -
-Implementation - - -

-fun get_token_amount(exchange_rate: &PoolTokenExchangeRate, iota_amount: u64): u64 \{
-    // When either amount is 0, that means we have no stakes with this pool.
-    // The other amount might be non-zero when there's dust left in the pool.
-    if (exchange_rate.iota_amount == 0 || exchange_rate.pool_token_amount == 0) \{
-        return iota_amount
-    };
-    let res = exchange_rate.pool_token_amount as u128
-            * (iota_amount as u128)
-            / (exchange_rate.iota_amount as u128);
-    res as u64
-}
-
- - - -
- - - -## Function `initial_exchange_rate` - - - -

-fun initial_exchange_rate(): staking_pool::PoolTokenExchangeRate
-
- - - -
-Implementation - - -

-fun initial_exchange_rate(): PoolTokenExchangeRate \{
-    PoolTokenExchangeRate \{ iota_amount: 0, pool_token_amount: 0 }
-}
-
- - - -
- - - -## Function `check_balance_invariants` - - - -

-fun check_balance_invariants(pool: &staking_pool::StakingPool, epoch: u64)
-
- - - -
-Implementation - - -

-fun check_balance_invariants(pool: &StakingPool, epoch: u64) \{
-    let exchange_rate = pool_token_exchange_rate_at_epoch(pool, epoch);
-    // check that the pool token balance and iota balance ratio matches the exchange rate stored.
-    let expected = get_token_amount(&exchange_rate, pool.iota_balance);
-    let actual = pool.pool_token_balance;
-    assert!(expected == actual, ETokenBalancesDoNotMatchExchangeRate)
-}
-
- - - -
diff --git a/crates/iota-framework/docs/iota-system/storage_fund.mdx b/crates/iota-framework/docs/iota-system/storage_fund.mdx deleted file mode 100644 index b4687209959..00000000000 --- a/crates/iota-framework/docs/iota-system/storage_fund.mdx +++ /dev/null @@ -1,202 +0,0 @@ ---- -title: Module `0x3::storage_fund` ---- -import Link from '@docusaurus/Link'; - - - - -- [Struct `StorageFund`](#0x3_storage_fund_StorageFund) -- [Function `new`](#0x3_storage_fund_new) -- [Function `advance_epoch`](#0x3_storage_fund_advance_epoch) -- [Function `total_object_storage_rebates`](#0x3_storage_fund_total_object_storage_rebates) -- [Function `total_balance`](#0x3_storage_fund_total_balance) - - -

-use 0x2::balance;
-use 0x2::iota;
-
- - - - - -## Struct `StorageFund` - -Struct representing the storage fund, containing two -Balances: -- -total_object_storage_rebates has the invariant that it's the sum of -storage_rebate of -all objects currently stored on-chain. To maintain this invariant, the only inflow of this -balance is storage charges collected from transactions, and the only outflow is storage rebates -of transactions, including both the portion refunded to the transaction senders as well as -the non-refundable portion taken out and put into -non_refundable_balance. -- -non_refundable_balance contains any remaining inflow of the storage fund that should not -be taken out of the fund. - - -

-struct StorageFund has store
-
- - - -
-Fields - - -
-
- -total_object_storage_rebates: balance::Balance<iota::IOTA> -
-
- -
-
- -non_refundable_balance: balance::Balance<iota::IOTA> -
-
- -
-
- - -
- - - -## Function `new` - -Called by -iota_system at genesis time. - - -

-public(friend) fun new(initial_fund: balance::Balance<iota::IOTA>): storage_fund::StorageFund
-
- - - -
-Implementation - - -

-public(package) fun new(initial_fund: Balance<IOTA>) : StorageFund \{
-    StorageFund \{
-        // At the beginning there's no object in the storage yet
-        total_object_storage_rebates: balance::zero(),
-        non_refundable_balance: initial_fund,
-    }
-}
-
- - - -
- - - -## Function `advance_epoch` - -Called by -iota_system at epoch change times to process the inflows and outflows of storage fund. - - -

-public(friend) fun advance_epoch(self: &mut storage_fund::StorageFund, storage_charges: balance::Balance<iota::IOTA>, storage_rebate_amount: u64, non_refundable_storage_fee_amount: u64): balance::Balance<iota::IOTA>
-
- - - -
-Implementation - - -

-public(package) fun advance_epoch(
-    self: &mut StorageFund,
-    storage_charges: Balance<IOTA>,
-    storage_rebate_amount: u64,
-    non_refundable_storage_fee_amount: u64,
-) : Balance<IOTA> \{
-    // The storage charges for the epoch come from the storage rebate of the new objects created
-    // and the new storage rebates of the objects modified during the epoch so we put the charges
-    // into `total_object_storage_rebates`.
-    self.total_object_storage_rebates.join(storage_charges);
-
-    // Split out the non-refundable portion of the storage rebate and put it into the non-refundable balance.
-    let non_refundable_storage_fee = self.total_object_storage_rebates.split(non_refundable_storage_fee_amount);
-    self.non_refundable_balance.join(non_refundable_storage_fee);
-
-    // `storage_rebates` include the already refunded rebates of deleted objects and old rebates of modified objects and
-    // should be taken out of the `total_object_storage_rebates`.
-    let storage_rebate = self.total_object_storage_rebates.split(storage_rebate_amount);
-
-    // The storage rebate has already been returned to individual transaction senders' gas coins
-    // so we return the balance to be burnt at the very end of epoch change.
-    storage_rebate
-}
-
- - - -
- - - -## Function `total_object_storage_rebates` - - - -

-public fun total_object_storage_rebates(self: &storage_fund::StorageFund): u64
-
- - - -
-Implementation - - -

-public fun total_object_storage_rebates(self: &StorageFund): u64 \{
-    self.total_object_storage_rebates.value()
-}
-
- - - -
- - - -## Function `total_balance` - - - -

-public fun total_balance(self: &storage_fund::StorageFund): u64
-
- - - -
-Implementation - - -

-public fun total_balance(self: &StorageFund): u64 \{
-    self.total_object_storage_rebates.value() + self.non_refundable_balance.value()
-}
-
- - - -
diff --git a/crates/iota-framework/docs/iota-system/timelocked_staking.mdx b/crates/iota-framework/docs/iota-system/timelocked_staking.mdx deleted file mode 100644 index ba72485edc7..00000000000 --- a/crates/iota-framework/docs/iota-system/timelocked_staking.mdx +++ /dev/null @@ -1,926 +0,0 @@ ---- -title: Module `0x3::timelocked_staking` ---- -import Link from '@docusaurus/Link'; - - - - -- [Resource `TimelockedStakedIota`](#0x3_timelocked_staking_TimelockedStakedIota) -- [Constants](#@Constants_0) -- [Function `request_add_stake`](#0x3_timelocked_staking_request_add_stake) -- [Function `request_add_stake_mul_bal`](#0x3_timelocked_staking_request_add_stake_mul_bal) -- [Function `request_withdraw_stake`](#0x3_timelocked_staking_request_withdraw_stake) -- [Function `request_add_stake_non_entry`](#0x3_timelocked_staking_request_add_stake_non_entry) -- [Function `request_add_stake_mul_bal_non_entry`](#0x3_timelocked_staking_request_add_stake_mul_bal_non_entry) -- [Function `request_withdraw_stake_non_entry`](#0x3_timelocked_staking_request_withdraw_stake_non_entry) -- [Function `split`](#0x3_timelocked_staking_split) -- [Function `split_staked_iota`](#0x3_timelocked_staking_split_staked_iota) -- [Function `join_staked_iota`](#0x3_timelocked_staking_join_staked_iota) -- [Function `transfer_to_sender`](#0x3_timelocked_staking_transfer_to_sender) -- [Function `transfer_to_sender_multiple`](#0x3_timelocked_staking_transfer_to_sender_multiple) -- [Function `is_equal_staking_metadata`](#0x3_timelocked_staking_is_equal_staking_metadata) -- [Function `pool_id`](#0x3_timelocked_staking_pool_id) -- [Function `staked_iota_amount`](#0x3_timelocked_staking_staked_iota_amount) -- [Function `stake_activation_epoch`](#0x3_timelocked_staking_stake_activation_epoch) -- [Function `expiration_timestamp_ms`](#0x3_timelocked_staking_expiration_timestamp_ms) -- [Function `label`](#0x3_timelocked_staking_label) -- [Function `is_labeled_with`](#0x3_timelocked_staking_is_labeled_with) -- [Function `unpack`](#0x3_timelocked_staking_unpack) -- [Function `transfer`](#0x3_timelocked_staking_transfer) -- [Function `transfer_multiple`](#0x3_timelocked_staking_transfer_multiple) -- [Function `request_add_stake_at_genesis`](#0x3_timelocked_staking_request_add_stake_at_genesis) - - -

-use 0x1::option;
-use 0x1::string;
-use 0x1::vector;
-use 0x2::balance;
-use 0x2::coin;
-use 0x2::iota;
-use 0x2::object;
-use 0x2::timelock;
-use 0x2::transfer;
-use 0x2::tx_context;
-use 0x3::iota_system;
-use 0x3::staking_pool;
-use 0x3::validator;
-
- - - - - -## Resource `TimelockedStakedIota` - -A self-custodial object holding the timelocked staked IOTA tokens. - - -

-struct TimelockedStakedIota has key
-
- - - -
-Fields - - -
-
- -id: object::UID -
-
- -
-
- -staked_iota: staking_pool::StakedIota -
-
- A self-custodial object holding the staked IOTA tokens. -
-
- -expiration_timestamp_ms: u64 -
-
- This is the epoch time stamp of when the lock expires. -
-
- -label: option::Option<string::String> -
-
- Timelock related label. -
-
- - -
- - - -## Constants - - - - -Incompatible objects when joining TimelockedStakedIota - - -

-const EIncompatibleTimelockedStakedIota: u64 = 1;
-
- - - - - -For when trying to stake an expired time-locked balance. - - -

-const ETimeLockShouldNotBeExpired: u64 = 0;
-
- - - - - -## Function `request_add_stake` - -Add a time-locked stake to a validator's staking pool. - - -

-public entry fun request_add_stake(iota_system: &mut iota_system::IotaSystemState, timelocked_balance: timelock::TimeLock<balance::Balance<iota::IOTA>>, validator_address: address, ctx: &mut tx_context::TxContext)
-
- - - -
-Implementation - - -

-public entry fun request_add_stake(
-    iota_system: &mut IotaSystemState,
-    timelocked_balance: TimeLock<Balance<IOTA>>,
-    validator_address: address,
-    ctx: &mut TxContext,
-) \{
-    // Stake the time-locked balance.
-    let timelocked_staked_iota = request_add_stake_non_entry(iota_system, timelocked_balance, validator_address, ctx);
-
-    // Transfer the receipt to the sender.
-    timelocked_staked_iota.transfer_to_sender(ctx);
-}
-
- - - -
- - - -## Function `request_add_stake_mul_bal` - -Add a time-locked stake to a validator's staking pool using multiple time-locked balances. - - -

-public entry fun request_add_stake_mul_bal(iota_system: &mut iota_system::IotaSystemState, timelocked_balances: vector<timelock::TimeLock<balance::Balance<iota::IOTA>>>, validator_address: address, ctx: &mut tx_context::TxContext)
-
- - - -
-Implementation - - -

-public entry fun request_add_stake_mul_bal(
-    iota_system: &mut IotaSystemState,
-    timelocked_balances: vector<TimeLock<Balance<IOTA>>>,
-    validator_address: address,
-    ctx: &mut TxContext,
-) \{
-    // Stake the time-locked balances.
-    let mut receipts = request_add_stake_mul_bal_non_entry(iota_system, timelocked_balances, validator_address, ctx);
-
-    // Create useful variables.
-    let (mut i, len) = (0, receipts.length());
-
-    // Send all the receipts to the sender.
-    while (i < len) \{
-        // Take a receipt.
-        let receipt = receipts.pop_back();
-
-        // Transfer the receipt to the sender.
-        receipt.transfer_to_sender(ctx);
-
-        i = i + 1
-    };
-
-    // Destroy the empty vector.
-    vector::destroy_empty(receipts)
-}
-
- - - -
- - - -## Function `request_withdraw_stake` - -Withdraw a time-locked stake from a validator's staking pool. - - -

-public entry fun request_withdraw_stake(iota_system: &mut iota_system::IotaSystemState, timelocked_staked_iota: timelocked_staking::TimelockedStakedIota, ctx: &mut tx_context::TxContext)
-
- - - -
-Implementation - - -

-public entry fun request_withdraw_stake(
-    iota_system: &mut IotaSystemState,
-    timelocked_staked_iota: TimelockedStakedIota,
-    ctx: &mut TxContext,
-) \{
-    // Withdraw the time-locked balance.
-    let (timelocked_balance, reward) = request_withdraw_stake_non_entry(iota_system, timelocked_staked_iota, ctx);
-
-    // Transfer the withdrawn time-locked balance to the sender.
-   timelocked_balance.transfer_to_sender(ctx);
-
-    // Send coins only if the reward is not zero.
-    if (reward.value() > 0) \{
-        transfer::public_transfer(reward.into_coin(ctx), ctx.sender());
-    }
-    else \{
-        balance::destroy_zero(reward);
-    }
-}
-
- - - -
- - - -## Function `request_add_stake_non_entry` - -The non-entry version of -request_add_stake, which returns the time-locked staked IOTA instead of transferring it to the sender. - - -

-public fun request_add_stake_non_entry(iota_system: &mut iota_system::IotaSystemState, timelocked_balance: timelock::TimeLock<balance::Balance<iota::IOTA>>, validator_address: address, ctx: &mut tx_context::TxContext): timelocked_staking::TimelockedStakedIota
-
- - - -
-Implementation - - -

-public fun request_add_stake_non_entry(
-    iota_system: &mut IotaSystemState,
-    timelocked_balance: TimeLock<Balance<IOTA>>,
-    validator_address: address,
-    ctx: &mut TxContext,
-) : TimelockedStakedIota \{
-    // Check the preconditions.
-    assert!(timelocked_balance.is_locked(ctx), ETimeLockShouldNotBeExpired);
-
-    // Unpack the time-locked balance.
-    let sys_timelock_cap = iota_system.load_system_timelock_cap();
-    let (balance, expiration_timestamp_ms, label) = timelock::system_unpack(sys_timelock_cap, timelocked_balance);
-
-    // Stake the time-locked balance.
-    let staked_iota = iota_system.request_add_stake_non_entry(
-        balance.into_coin(ctx),
-        validator_address,
-        ctx,
-    );
-
-    // Create and return a receipt.
-    TimelockedStakedIota \{
-        id: object::new(ctx),
-        staked_iota,
-        expiration_timestamp_ms,
-        label,
-    }
-}
-
- - - -
- - - -## Function `request_add_stake_mul_bal_non_entry` - -The non-entry version of -request_add_stake_mul_bal, -which returns a list of the time-locked staked IOTAs instead of transferring them to the sender. - - -

-public fun request_add_stake_mul_bal_non_entry(iota_system: &mut iota_system::IotaSystemState, timelocked_balances: vector<timelock::TimeLock<balance::Balance<iota::IOTA>>>, validator_address: address, ctx: &mut tx_context::TxContext): vector<timelocked_staking::TimelockedStakedIota>
-
- - - -
-Implementation - - -

-public fun request_add_stake_mul_bal_non_entry(
-    iota_system: &mut IotaSystemState,
-    mut timelocked_balances: vector<TimeLock<Balance<IOTA>>>,
-    validator_address: address,
-    ctx: &mut TxContext,
-) : vector<TimelockedStakedIota> \{
-    // Create a vector to store the results.
-    let mut result = vector[];
-
-    // Create useful variables.
-    let (mut i, len) = (0, timelocked_balances.length());
-
-    // Stake all the time-locked balances.
-    while (i < len) \{
-        // Take a time-locked balance.
-        let timelocked_balance = timelocked_balances.pop_back();
-
-        // Stake the time-locked balance.
-        let timelocked_staked_iota = request_add_stake_non_entry(iota_system, timelocked_balance, validator_address, ctx);
-
-        // Store the created receipt.
-        result.push_back(timelocked_staked_iota);
-
-        i = i + 1
-    };
-
-    // Destroy the empty vector.
-    vector::destroy_empty(timelocked_balances);
-
-    result
-}
-
- - - -
- - - -## Function `request_withdraw_stake_non_entry` - -Non-entry version of -request_withdraw_stake that returns the withdrawn time-locked IOTA and reward -instead of transferring it to the sender. - - -

-public fun request_withdraw_stake_non_entry(iota_system: &mut iota_system::IotaSystemState, timelocked_staked_iota: timelocked_staking::TimelockedStakedIota, ctx: &mut tx_context::TxContext): (timelock::TimeLock<balance::Balance<iota::IOTA>>, balance::Balance<iota::IOTA>)
-
- - - -
-Implementation - - -

-public fun request_withdraw_stake_non_entry(
-    iota_system: &mut IotaSystemState,
-    timelocked_staked_iota: TimelockedStakedIota,
-    ctx: &mut TxContext,
-) : (TimeLock<Balance<IOTA>>, Balance<IOTA>) \{
-    // Unpack the `TimelockedStakedIota` instance.
-    let (staked_iota, expiration_timestamp_ms, label) = timelocked_staked_iota.unpack();
-
-    // Store the original stake amount.
-    let principal = staked_iota.staked_iota_amount();
-
-    // Withdraw the balance.
-    let mut withdraw_stake = iota_system.request_withdraw_stake_non_entry(staked_iota, ctx);
-
-    // The iota_system withdraw functions return a balance that consists of the original staked amount plus the reward amount;
-    // In here, it splits the original staked balance to timelock it again.
-    let principal = withdraw_stake.split(principal);
-
-    // Pack and return a time-locked balance, and the reward.
-    let sys_timelock_cap = iota_system.load_system_timelock_cap();
-    (timelock::system_pack(sys_timelock_cap, principal, expiration_timestamp_ms, label, ctx), withdraw_stake)
-}
-
- - - -
- - - -## Function `split` - -Split -TimelockedStakedIota into two parts, one with principal -split_amount, -and the remaining principal is left in -self. -All the other parameters of the -TimelockedStakedIota like -stake_activation_epoch or -pool_id remain the same. - - -

-public fun split(self: &mut timelocked_staking::TimelockedStakedIota, split_amount: u64, ctx: &mut tx_context::TxContext): timelocked_staking::TimelockedStakedIota
-
- - - -
-Implementation - - -

-public fun split(self: &mut TimelockedStakedIota, split_amount: u64, ctx: &mut TxContext): TimelockedStakedIota \{
-    let split_stake = self.staked_iota.split(split_amount, ctx);
-
-    TimelockedStakedIota \{
-        id: object::new(ctx),
-        staked_iota: split_stake,
-        expiration_timestamp_ms: self.expiration_timestamp_ms,
-        label: self.label,
-    }
-}
-
- - - -
- - - -## Function `split_staked_iota` - -Split the given -TimelockedStakedIota to the two parts, one with principal -split_amount, -transfer the newly split part to the sender address. - - -

-public entry fun split_staked_iota(stake: &mut timelocked_staking::TimelockedStakedIota, split_amount: u64, ctx: &mut tx_context::TxContext)
-
- - - -
-Implementation - - -

-public entry fun split_staked_iota(stake: &mut TimelockedStakedIota, split_amount: u64, ctx: &mut TxContext) \{
-    split(stake, split_amount, ctx).transfer_to_sender(ctx);
-}
-
- - - -
- - - -## Function `join_staked_iota` - -Consume the staked iota -other and add its value to -self. -Aborts if some of the staking parameters are incompatible (pool id, stake activation epoch, etc.) - - -

-public entry fun join_staked_iota(self: &mut timelocked_staking::TimelockedStakedIota, other: timelocked_staking::TimelockedStakedIota)
-
- - - -
-Implementation - - -

-public entry fun join_staked_iota(self: &mut TimelockedStakedIota, other: TimelockedStakedIota) \{
-    assert!(self.is_equal_staking_metadata(&other), EIncompatibleTimelockedStakedIota);
-
-    let TimelockedStakedIota \{
-        id,
-        staked_iota,
-        expiration_timestamp_ms: _,
-        label: _,
-    } = other;
-
-    id.delete();
-
-    self.staked_iota.join(staked_iota);
-}
-
- - - -
- - - -## Function `transfer_to_sender` - -A utility function to transfer a -TimelockedStakedIota. - - -

-public fun transfer_to_sender(stake: timelocked_staking::TimelockedStakedIota, ctx: &tx_context::TxContext)
-
- - - -
-Implementation - - -

-public fun transfer_to_sender(stake: TimelockedStakedIota, ctx: &TxContext) \{
-    transfer(stake, ctx.sender())
-}
-
- - - -
- - - -## Function `transfer_to_sender_multiple` - -A utility function to transfer multiple -TimelockedStakedIota. - - -

-public fun transfer_to_sender_multiple(stakes: vector<timelocked_staking::TimelockedStakedIota>, ctx: &tx_context::TxContext)
-
- - - -
-Implementation - - -

-public fun transfer_to_sender_multiple(stakes: vector<TimelockedStakedIota>, ctx: &TxContext) \{
-    transfer_multiple(stakes, ctx.sender())
-}
-
- - - -
- - - -## Function `is_equal_staking_metadata` - -A utility function that returns true if all the staking parameters -of the staked iota except the principal are identical - - -

-public fun is_equal_staking_metadata(self: &timelocked_staking::TimelockedStakedIota, other: &timelocked_staking::TimelockedStakedIota): bool
-
- - - -
-Implementation - - -

-public fun is_equal_staking_metadata(self: &TimelockedStakedIota, other: &TimelockedStakedIota): bool \{
-    self.staked_iota.is_equal_staking_metadata(&other.staked_iota) &&
-    (self.expiration_timestamp_ms == other.expiration_timestamp_ms) &&
-    (self.label() == other.label())
-}
-
- - - -
- - - -## Function `pool_id` - -Function to get the pool id of a -TimelockedStakedIota. - - -

-public fun pool_id(self: &timelocked_staking::TimelockedStakedIota): object::ID
-
- - - -
-Implementation - - -

-public fun pool_id(self: &TimelockedStakedIota): ID \{ self.staked_iota.pool_id() }
-
- - - -
- - - -## Function `staked_iota_amount` - -Function to get the staked iota amount of a -TimelockedStakedIota. - - -

-public fun staked_iota_amount(self: &timelocked_staking::TimelockedStakedIota): u64
-
- - - -
-Implementation - - -

-public fun staked_iota_amount(self: &TimelockedStakedIota): u64 \{ self.staked_iota.staked_iota_amount() }
-
- - - -
- - - -## Function `stake_activation_epoch` - -Function to get the stake activation epoch of a -TimelockedStakedIota. - - -

-public fun stake_activation_epoch(self: &timelocked_staking::TimelockedStakedIota): u64
-
- - - -
-Implementation - - -

-public fun stake_activation_epoch(self: &TimelockedStakedIota): u64 \{
-    self.staked_iota.stake_activation_epoch()
-}
-
- - - -
- - - -## Function `expiration_timestamp_ms` - -Function to get the expiration timestamp of a -TimelockedStakedIota. - - -

-public fun expiration_timestamp_ms(self: &timelocked_staking::TimelockedStakedIota): u64
-
- - - -
-Implementation - - -

-public fun expiration_timestamp_ms(self: &TimelockedStakedIota): u64 \{
-    self.expiration_timestamp_ms
-}
-
- - - -
- - - -## Function `label` - -Function to get the label of a -TimelockedStakedIota. - - -

-public fun label(self: &timelocked_staking::TimelockedStakedIota): option::Option<string::String>
-
- - - -
-Implementation - - -

-public fun label(self: &TimelockedStakedIota): Option<String> \{
-    self.label
-}
-
- - - -
- - - -## Function `is_labeled_with` - -Check if a -TimelockedStakedIota is labeled with the type -L. - - -

-public fun is_labeled_with<L>(self: &timelocked_staking::TimelockedStakedIota): bool
-
- - - -
-Implementation - - -

-public fun is_labeled_with<L>(self: &TimelockedStakedIota): bool \{
-    if (self.label.is_some()) \{
-        self.label.borrow() == timelock::type_name<L>()
-    }
-    else \{
-        false
-    }
-}
-
- - - -
- - - -## Function `unpack` - -A utility function to destroy a -TimelockedStakedIota. - - -

-fun unpack(self: timelocked_staking::TimelockedStakedIota): (staking_pool::StakedIota, u64, option::Option<string::String>)
-
- - - -
-Implementation - - -

-fun unpack(self: TimelockedStakedIota): (StakedIota, u64, Option<String>) \{
-    let TimelockedStakedIota \{
-        id,
-        staked_iota,
-        expiration_timestamp_ms,
-        label,
-    } = self;
-
-    object::delete(id);
-
-    (staked_iota, expiration_timestamp_ms, label)
-}
-
- - - -
- - - -## Function `transfer` - -A utility function to transfer a -TimelockedStakedIota to a receiver. - - -

-fun transfer(stake: timelocked_staking::TimelockedStakedIota, receiver: address)
-
- - - -
-Implementation - - -

-fun transfer(stake: TimelockedStakedIota, receiver: address) \{
-    transfer::transfer(stake, receiver);
-}
-
- - - -
- - - -## Function `transfer_multiple` - -A utility function to transfer a vector of -TimelockedStakedIota to a receiver. - - -

-fun transfer_multiple(stakes: vector<timelocked_staking::TimelockedStakedIota>, receiver: address)
-
- - - -
-Implementation - - -

-fun transfer_multiple(mut stakes: vector<TimelockedStakedIota>, receiver: address) \{
-    // Transfer all the time-locked stakes to the recipient.
-    while (!stakes.is_empty()) \{
-       let stake = stakes.pop_back();
-       transfer::transfer(stake, receiver);
-    };
-
-    // Destroy the empty vector.
-    vector::destroy_empty(stakes);
-}
-
- - - -
- - - -## Function `request_add_stake_at_genesis` - -Request to add timelocked stake to the validator's staking pool at genesis - - -

-public(friend) fun request_add_stake_at_genesis(validator: &mut validator::Validator, stake: balance::Balance<iota::IOTA>, staker_address: address, expiration_timestamp_ms: u64, label: option::Option<string::String>, ctx: &mut tx_context::TxContext)
-
- - - -
-Implementation - - -

-public(package) fun request_add_stake_at_genesis(
-    validator: &mut Validator,
-    stake: Balance<IOTA>,
-    staker_address: address,
-    expiration_timestamp_ms: u64,
-    label: Option<String>,
-    ctx: &mut TxContext,
-) \{
-    let staked_iota = validator.request_add_stake_at_genesis_with_receipt(stake, ctx);
-    let timelocked_staked_iota = TimelockedStakedIota \{
-        id: object::new(ctx),
-        staked_iota,
-        expiration_timestamp_ms,
-        label,
-    };
-    transfer(timelocked_staked_iota, staker_address);
-}
-
- - - -
diff --git a/crates/iota-framework/docs/iota-system/validator.mdx b/crates/iota-framework/docs/iota-system/validator.mdx deleted file mode 100644 index 9d83fb0552b..00000000000 --- a/crates/iota-framework/docs/iota-system/validator.mdx +++ /dev/null @@ -1,3171 +0,0 @@ ---- -title: Module `0x3::validator` ---- -import Link from '@docusaurus/Link'; - - - - -- [Struct `ValidatorMetadata`](#0x3_validator_ValidatorMetadata) -- [Struct `Validator`](#0x3_validator_Validator) -- [Struct `StakingRequestEvent`](#0x3_validator_StakingRequestEvent) -- [Struct `UnstakingRequestEvent`](#0x3_validator_UnstakingRequestEvent) -- [Constants](#@Constants_0) -- [Function `new_metadata`](#0x3_validator_new_metadata) -- [Function `new`](#0x3_validator_new) -- [Function `deactivate`](#0x3_validator_deactivate) -- [Function `activate`](#0x3_validator_activate) -- [Function `adjust_stake_and_gas_price`](#0x3_validator_adjust_stake_and_gas_price) -- [Function `request_add_stake`](#0x3_validator_request_add_stake) -- [Function `request_add_stake_at_genesis`](#0x3_validator_request_add_stake_at_genesis) -- [Function `request_add_stake_at_genesis_with_receipt`](#0x3_validator_request_add_stake_at_genesis_with_receipt) -- [Function `request_withdraw_stake`](#0x3_validator_request_withdraw_stake) -- [Function `request_set_gas_price`](#0x3_validator_request_set_gas_price) -- [Function `set_candidate_gas_price`](#0x3_validator_set_candidate_gas_price) -- [Function `request_set_commission_rate`](#0x3_validator_request_set_commission_rate) -- [Function `set_candidate_commission_rate`](#0x3_validator_set_candidate_commission_rate) -- [Function `deposit_stake_rewards`](#0x3_validator_deposit_stake_rewards) -- [Function `process_pending_stakes_and_withdraws`](#0x3_validator_process_pending_stakes_and_withdraws) -- [Function `is_preactive`](#0x3_validator_is_preactive) -- [Function `metadata`](#0x3_validator_metadata) -- [Function `iota_address`](#0x3_validator_iota_address) -- [Function `name`](#0x3_validator_name) -- [Function `description`](#0x3_validator_description) -- [Function `image_url`](#0x3_validator_image_url) -- [Function `project_url`](#0x3_validator_project_url) -- [Function `network_address`](#0x3_validator_network_address) -- [Function `p2p_address`](#0x3_validator_p2p_address) -- [Function `primary_address`](#0x3_validator_primary_address) -- [Function `worker_address`](#0x3_validator_worker_address) -- [Function `protocol_pubkey_bytes`](#0x3_validator_protocol_pubkey_bytes) -- [Function `proof_of_possession`](#0x3_validator_proof_of_possession) -- [Function `network_pubkey_bytes`](#0x3_validator_network_pubkey_bytes) -- [Function `worker_pubkey_bytes`](#0x3_validator_worker_pubkey_bytes) -- [Function `next_epoch_network_address`](#0x3_validator_next_epoch_network_address) -- [Function `next_epoch_p2p_address`](#0x3_validator_next_epoch_p2p_address) -- [Function `next_epoch_primary_address`](#0x3_validator_next_epoch_primary_address) -- [Function `next_epoch_worker_address`](#0x3_validator_next_epoch_worker_address) -- [Function `next_epoch_protocol_pubkey_bytes`](#0x3_validator_next_epoch_protocol_pubkey_bytes) -- [Function `next_epoch_proof_of_possession`](#0x3_validator_next_epoch_proof_of_possession) -- [Function `next_epoch_network_pubkey_bytes`](#0x3_validator_next_epoch_network_pubkey_bytes) -- [Function `next_epoch_worker_pubkey_bytes`](#0x3_validator_next_epoch_worker_pubkey_bytes) -- [Function `operation_cap_id`](#0x3_validator_operation_cap_id) -- [Function `next_epoch_gas_price`](#0x3_validator_next_epoch_gas_price) -- [Function `total_stake_amount`](#0x3_validator_total_stake_amount) -- [Function `stake_amount`](#0x3_validator_stake_amount) -- [Function `total_stake`](#0x3_validator_total_stake) -- [Function `voting_power`](#0x3_validator_voting_power) -- [Function `set_voting_power`](#0x3_validator_set_voting_power) -- [Function `pending_stake_amount`](#0x3_validator_pending_stake_amount) -- [Function `pending_stake_withdraw_amount`](#0x3_validator_pending_stake_withdraw_amount) -- [Function `gas_price`](#0x3_validator_gas_price) -- [Function `commission_rate`](#0x3_validator_commission_rate) -- [Function `pool_token_exchange_rate_at_epoch`](#0x3_validator_pool_token_exchange_rate_at_epoch) -- [Function `staking_pool_id`](#0x3_validator_staking_pool_id) -- [Function `is_duplicate`](#0x3_validator_is_duplicate) -- [Function `is_equal_some_and_value`](#0x3_validator_is_equal_some_and_value) -- [Function `is_equal_some`](#0x3_validator_is_equal_some) -- [Function `new_unverified_validator_operation_cap_and_transfer`](#0x3_validator_new_unverified_validator_operation_cap_and_transfer) -- [Function `update_name`](#0x3_validator_update_name) -- [Function `update_description`](#0x3_validator_update_description) -- [Function `update_image_url`](#0x3_validator_update_image_url) -- [Function `update_project_url`](#0x3_validator_update_project_url) -- [Function `update_next_epoch_network_address`](#0x3_validator_update_next_epoch_network_address) -- [Function `update_candidate_network_address`](#0x3_validator_update_candidate_network_address) -- [Function `update_next_epoch_p2p_address`](#0x3_validator_update_next_epoch_p2p_address) -- [Function `update_candidate_p2p_address`](#0x3_validator_update_candidate_p2p_address) -- [Function `update_next_epoch_primary_address`](#0x3_validator_update_next_epoch_primary_address) -- [Function `update_candidate_primary_address`](#0x3_validator_update_candidate_primary_address) -- [Function `update_next_epoch_worker_address`](#0x3_validator_update_next_epoch_worker_address) -- [Function `update_candidate_worker_address`](#0x3_validator_update_candidate_worker_address) -- [Function `update_next_epoch_protocol_pubkey`](#0x3_validator_update_next_epoch_protocol_pubkey) -- [Function `update_candidate_protocol_pubkey`](#0x3_validator_update_candidate_protocol_pubkey) -- [Function `update_next_epoch_network_pubkey`](#0x3_validator_update_next_epoch_network_pubkey) -- [Function `update_candidate_network_pubkey`](#0x3_validator_update_candidate_network_pubkey) -- [Function `update_next_epoch_worker_pubkey`](#0x3_validator_update_next_epoch_worker_pubkey) -- [Function `update_candidate_worker_pubkey`](#0x3_validator_update_candidate_worker_pubkey) -- [Function `effectuate_staged_metadata`](#0x3_validator_effectuate_staged_metadata) -- [Function `validate_metadata`](#0x3_validator_validate_metadata) -- [Function `validate_metadata_bcs`](#0x3_validator_validate_metadata_bcs) -- [Function `get_staking_pool_ref`](#0x3_validator_get_staking_pool_ref) -- [Function `new_from_metadata`](#0x3_validator_new_from_metadata) - - -

-use 0x1::ascii;
-use 0x1::bcs;
-use 0x1::option;
-use 0x1::string;
-use 0x2::bag;
-use 0x2::balance;
-use 0x2::event;
-use 0x2::iota;
-use 0x2::object;
-use 0x2::transfer;
-use 0x2::tx_context;
-use 0x2::url;
-use 0x3::staking_pool;
-use 0x3::validator_cap;
-
- - - - - -## Struct `ValidatorMetadata` - - - -

-struct ValidatorMetadata has store
-
- - - -
-Fields - - -
-
- -iota_address: address -
-
- The Iota Address of the validator. This is the sender that created the Validator object, - and also the address to send validator/coins to during withdraws. -
-
- -protocol_pubkey_bytes: vector<u8> -
-
- The public key bytes corresponding to the private key that the validator - holds to sign transactions. For now, this is the same as AuthorityName. -
-
- -network_pubkey_bytes: vector<u8> -
-
- The public key bytes corresponding to the private key that the validator - uses to establish TLS connections -
-
- -worker_pubkey_bytes: vector<u8> -
-
- The public key bytes correstponding to the Narwhal Worker -
-
- -proof_of_possession: vector<u8> -
-
- This is a proof that the validator has ownership of the private key -
-
- -name: string::String -
-
- A unique human-readable name of this validator. -
-
- -description: string::String -
-
- -
-
- -image_url: url::Url -
-
- -
-
- -project_url: url::Url -
-
- -
-
- -net_address: string::String -
-
- The network address of the validator (could also contain extra info such as port, DNS and etc.). -
-
- -p2p_address: string::String -
-
- The address of the validator used for p2p activities such as state sync (could also contain extra info such as port, DNS and etc.). -
-
- -primary_address: string::String -
-
- The address of the narwhal primary -
-
- -worker_address: string::String -
-
- The address of the narwhal worker -
-
- -next_epoch_protocol_pubkey_bytes: option::Option<vector<u8>> -
-
- "next_epoch" metadata only takes effects in the next epoch. - If none, current value will stay unchanged. -
-
- -next_epoch_proof_of_possession: option::Option<vector<u8>> -
-
- -
-
- -next_epoch_network_pubkey_bytes: option::Option<vector<u8>> -
-
- -
-
- -next_epoch_worker_pubkey_bytes: option::Option<vector<u8>> -
-
- -
-
- -next_epoch_net_address: option::Option<string::String> -
-
- -
-
- -next_epoch_p2p_address: option::Option<string::String> -
-
- -
-
- -next_epoch_primary_address: option::Option<string::String> -
-
- -
-
- -next_epoch_worker_address: option::Option<string::String> -
-
- -
-
- -extra_fields: bag::Bag -
-
- Any extra fields that's not defined statically. -
-
- - -
- - - -## Struct `Validator` - - - -

-struct Validator has store
-
- - - -
-Fields - - -
-
- -metadata: validator::ValidatorMetadata -
-
- Summary of the validator. -
-
- -voting_power: u64 -
-
- The voting power of this validator, which might be different from its - stake amount. -
-
- -operation_cap_id: object::ID -
-
- The ID of this validator's current valid -UnverifiedValidatorOperationCap -
-
- -gas_price: u64 -
-
- Gas price quote, updated only at end of epoch. -
-
- -staking_pool: staking_pool::StakingPool -
-
- Staking pool for this validator. -
-
- -commission_rate: u64 -
-
- Commission rate of the validator, in basis point. -
-
- -next_epoch_stake: u64 -
-
- Total amount of stake that would be active in the next epoch. -
-
- -next_epoch_gas_price: u64 -
-
- This validator's gas price quote for the next epoch. -
-
- -next_epoch_commission_rate: u64 -
-
- The commission rate of the validator starting the next epoch, in basis point. -
-
- -extra_fields: bag::Bag -
-
- Any extra fields that's not defined statically. -
-
- - -
- - - -## Struct `StakingRequestEvent` - -Event emitted when a new stake request is received. - - -

-struct StakingRequestEvent has copy, drop
-
- - - -
-Fields - - -
-
- -pool_id: object::ID -
-
- -
-
- -validator_address: address -
-
- -
-
- -staker_address: address -
-
- -
-
- -epoch: u64 -
-
- -
-
- -amount: u64 -
-
- -
-
- - -
- - - -## Struct `UnstakingRequestEvent` - -Event emitted when a new unstake request is received. - - -

-struct UnstakingRequestEvent has copy, drop
-
- - - -
-Fields - - -
-
- -pool_id: object::ID -
-
- -
-
- -validator_address: address -
-
- -
-
- -staker_address: address -
-
- -
-
- -stake_activation_epoch: u64 -
-
- -
-
- -unstaking_epoch: u64 -
-
- -
-
- -principal_amount: u64 -
-
- -
-
- -reward_amount: u64 -
-
- -
-
- - -
- - - -## Constants - - - - -Function called during non-genesis times. - - -

-const ECalledDuringNonGenesis: u64 = 12;
-
- - - - - -Commission rate set by the validator is higher than the threshold - - -

-const ECommissionRateTooHigh: u64 = 8;
-
- - - - - -Validator trying to set gas price higher than threshold. - - -

-const EGasPriceHigherThanThreshold: u64 = 102;
-
- - - - - -Capability code is not valid - - -

-const EInvalidCap: u64 = 101;
-
- - - - - -Invalid proof_of_possession field in ValidatorMetadata - - -

-const EInvalidProofOfPossession: u64 = 0;
-
- - - - - -Stake amount is invalid or wrong. - - -

-const EInvalidStakeAmount: u64 = 11;
-
- - - - - -Invalid net_address field in ValidatorMetadata - - -

-const EMetadataInvalidNetAddr: u64 = 4;
-
- - - - - -Invalid network_pubkey_bytes field in ValidatorMetadata - - -

-const EMetadataInvalidNetPubkey: u64 = 2;
-
- - - - - -Invalid p2p_address field in ValidatorMetadata - - -

-const EMetadataInvalidP2pAddr: u64 = 5;
-
- - - - - -Invalid primary_address field in ValidatorMetadata - - -

-const EMetadataInvalidPrimaryAddr: u64 = 6;
-
- - - - - -Invalid pubkey_bytes field in ValidatorMetadata - - -

-const EMetadataInvalidPubkey: u64 = 1;
-
- - - - - -Invalidworker_address field in ValidatorMetadata - - -

-const EMetadataInvalidWorkerAddr: u64 = 7;
-
- - - - - -Invalid worker_pubkey_bytes field in ValidatorMetadata - - -

-const EMetadataInvalidWorkerPubkey: u64 = 3;
-
- - - - - -New Capability is not created by the validator itself - - -

-const ENewCapNotCreatedByValidatorItself: u64 = 100;
-
- - - - - -Intended validator is not a candidate one. - - -

-const ENotValidatorCandidate: u64 = 10;
-
- - - - - -Validator Metadata is too long - - -

-const EValidatorMetadataExceedingLengthLimit: u64 = 9;
-
- - - - - - - -

-const MAX_COMMISSION_RATE: u64 = 2000;
-
- - - - - -Max gas price a validator can set is 100K MICROS. - - -

-const MAX_VALIDATOR_GAS_PRICE: u64 = 100000;
-
- - - - - - - -

-const MAX_VALIDATOR_METADATA_LENGTH: u64 = 256;
-
- - - - - -## Function `new_metadata` - - - -

-public(friend) fun new_metadata(iota_address: address, protocol_pubkey_bytes: vector<u8>, network_pubkey_bytes: vector<u8>, worker_pubkey_bytes: vector<u8>, proof_of_possession: vector<u8>, name: string::String, description: string::String, image_url: url::Url, project_url: url::Url, net_address: string::String, p2p_address: string::String, primary_address: string::String, worker_address: string::String, extra_fields: bag::Bag): validator::ValidatorMetadata
-
- - - -
-Implementation - - -

-public(package) fun new_metadata(
-    iota_address: address,
-    protocol_pubkey_bytes: vector<u8>,
-    network_pubkey_bytes: vector<u8>,
-    worker_pubkey_bytes: vector<u8>,
-    proof_of_possession: vector<u8>,
-    name: String,
-    description: String,
-    image_url: Url,
-    project_url: Url,
-    net_address: String,
-    p2p_address: String,
-    primary_address: String,
-    worker_address: String,
-    extra_fields: Bag,
-): ValidatorMetadata \{
-    let metadata = ValidatorMetadata \{
-        iota_address,
-        protocol_pubkey_bytes,
-        network_pubkey_bytes,
-        worker_pubkey_bytes,
-        proof_of_possession,
-        name,
-        description,
-        image_url,
-        project_url,
-        net_address,
-        p2p_address,
-        primary_address,
-        worker_address,
-        next_epoch_protocol_pubkey_bytes: option::none(),
-        next_epoch_network_pubkey_bytes: option::none(),
-        next_epoch_worker_pubkey_bytes: option::none(),
-        next_epoch_proof_of_possession: option::none(),
-        next_epoch_net_address: option::none(),
-        next_epoch_p2p_address: option::none(),
-        next_epoch_primary_address: option::none(),
-        next_epoch_worker_address: option::none(),
-        extra_fields,
-    };
-    metadata
-}
-
- - - -
- - - -## Function `new` - - - -

-public(friend) fun new(iota_address: address, protocol_pubkey_bytes: vector<u8>, network_pubkey_bytes: vector<u8>, worker_pubkey_bytes: vector<u8>, proof_of_possession: vector<u8>, name: vector<u8>, description: vector<u8>, image_url: vector<u8>, project_url: vector<u8>, net_address: vector<u8>, p2p_address: vector<u8>, primary_address: vector<u8>, worker_address: vector<u8>, gas_price: u64, commission_rate: u64, ctx: &mut tx_context::TxContext): validator::Validator
-
- - - -
-Implementation - - -

-public(package) fun new(
-    iota_address: address,
-    protocol_pubkey_bytes: vector<u8>,
-    network_pubkey_bytes: vector<u8>,
-    worker_pubkey_bytes: vector<u8>,
-    proof_of_possession: vector<u8>,
-    name: vector<u8>,
-    description: vector<u8>,
-    image_url: vector<u8>,
-    project_url: vector<u8>,
-    net_address: vector<u8>,
-    p2p_address: vector<u8>,
-    primary_address: vector<u8>,
-    worker_address: vector<u8>,
-    gas_price: u64,
-    commission_rate: u64,
-    ctx: &mut TxContext
-): Validator \{
-    assert!(
-        net_address.length() <= MAX_VALIDATOR_METADATA_LENGTH
-            && p2p_address.length() <= MAX_VALIDATOR_METADATA_LENGTH
-            && primary_address.length() <= MAX_VALIDATOR_METADATA_LENGTH
-            && worker_address.length() <= MAX_VALIDATOR_METADATA_LENGTH
-            && name.length() <= MAX_VALIDATOR_METADATA_LENGTH
-            && description.length() <= MAX_VALIDATOR_METADATA_LENGTH
-            && image_url.length() <= MAX_VALIDATOR_METADATA_LENGTH
-            && project_url.length() <= MAX_VALIDATOR_METADATA_LENGTH,
-        EValidatorMetadataExceedingLengthLimit
-    );
-    assert!(commission_rate <= MAX_COMMISSION_RATE, ECommissionRateTooHigh);
-    assert!(gas_price < MAX_VALIDATOR_GAS_PRICE, EGasPriceHigherThanThreshold);
-
-    let metadata = new_metadata(
-        iota_address,
-        protocol_pubkey_bytes,
-        network_pubkey_bytes,
-        worker_pubkey_bytes,
-        proof_of_possession,
-        name.to_ascii_string().to_string(),
-        description.to_ascii_string().to_string(),
-        url::new_unsafe_from_bytes(image_url),
-        url::new_unsafe_from_bytes(project_url),
-        net_address.to_ascii_string().to_string(),
-        p2p_address.to_ascii_string().to_string(),
-        primary_address.to_ascii_string().to_string(),
-        worker_address.to_ascii_string().to_string(),
-        bag::new(ctx),
-    );
-
-    // Checks that the keys & addresses & PoP are valid.
-    validate_metadata(&metadata);
-
-    new_from_metadata(
-        metadata,
-        gas_price,
-        commission_rate,
-        ctx
-    )
-}
-
- - - -
- - - -## Function `deactivate` - -Deactivate this validator's staking pool - - -

-public(friend) fun deactivate(self: &mut validator::Validator, deactivation_epoch: u64)
-
- - - -
-Implementation - - -

-public(package) fun deactivate(self: &mut Validator, deactivation_epoch: u64) \{
-    self.staking_pool.deactivate_staking_pool(deactivation_epoch)
-}
-
- - - -
- - - -## Function `activate` - - - -

-public(friend) fun activate(self: &mut validator::Validator, activation_epoch: u64)
-
- - - -
-Implementation - - -

-public(package) fun activate(self: &mut Validator, activation_epoch: u64) \{
-    self.staking_pool.activate_staking_pool(activation_epoch);
-}
-
- - - -
- - - -## Function `adjust_stake_and_gas_price` - -Process pending stake and pending withdraws, and update the gas price. - - -

-public(friend) fun adjust_stake_and_gas_price(self: &mut validator::Validator)
-
- - - -
-Implementation - - -

-public(package) fun adjust_stake_and_gas_price(self: &mut Validator) \{
-    self.gas_price = self.next_epoch_gas_price;
-    self.commission_rate = self.next_epoch_commission_rate;
-}
-
- - - -
- - - -## Function `request_add_stake` - -Request to add stake to the validator's staking pool, processed at the end of the epoch. - - -

-public(friend) fun request_add_stake(self: &mut validator::Validator, stake: balance::Balance<iota::IOTA>, staker_address: address, ctx: &mut tx_context::TxContext): staking_pool::StakedIota
-
- - - -
-Implementation - - -

-public(package) fun request_add_stake(
-    self: &mut Validator,
-    stake: Balance<IOTA>,
-    staker_address: address,
-    ctx: &mut TxContext,
-) : StakedIota \{
-    let stake_amount = stake.value();
-    assert!(stake_amount > 0, EInvalidStakeAmount);
-    let stake_epoch = ctx.epoch() + 1;
-    let staked_iota = self.staking_pool.request_add_stake(stake, stake_epoch, ctx);
-    // Process stake right away if staking pool is preactive.
-    if (self.staking_pool.is_preactive()) \{
-        self.staking_pool.process_pending_stake();
-    };
-    self.next_epoch_stake = self.next_epoch_stake + stake_amount;
-    event::emit(
-        StakingRequestEvent \{
-            pool_id: staking_pool_id(self),
-            validator_address: self.metadata.iota_address,
-            staker_address,
-            epoch: ctx.epoch(),
-            amount: stake_amount,
-        }
-    );
-    staked_iota
-}
-
- - - -
- - - -## Function `request_add_stake_at_genesis` - -Request to add stake to the validator's staking pool at genesis - - -

-public(friend) fun request_add_stake_at_genesis(self: &mut validator::Validator, stake: balance::Balance<iota::IOTA>, staker_address: address, ctx: &mut tx_context::TxContext)
-
- - - -
-Implementation - - -

-public(package) fun request_add_stake_at_genesis(
-    self: &mut Validator,
-    stake: Balance<IOTA>,
-    staker_address: address,
-    ctx: &mut TxContext,
-) \{
-    let staked_iota = request_add_stake_at_genesis_with_receipt(
-        self,
-        stake,
-        ctx
-    );
-    transfer::public_transfer(staked_iota, staker_address);
-}
-
- - - -
- - - -## Function `request_add_stake_at_genesis_with_receipt` - -Internal request to add stake to the validator's staking pool at genesis. -Returns a StakedIota - - -

-public(friend) fun request_add_stake_at_genesis_with_receipt(self: &mut validator::Validator, stake: balance::Balance<iota::IOTA>, ctx: &mut tx_context::TxContext): staking_pool::StakedIota
-
- - - -
-Implementation - - -

-public(package) fun request_add_stake_at_genesis_with_receipt(
-    self: &mut Validator,
-    stake: Balance<IOTA>,
-    ctx: &mut TxContext,
-) : StakedIota \{
-    assert!(ctx.epoch() == 0, ECalledDuringNonGenesis);
-    let stake_amount = stake.value();
-    assert!(stake_amount > 0, EInvalidStakeAmount);
-
-    let staked_iota = self.staking_pool.request_add_stake(
-        stake,
-        0, // epoch 0 -- genesis
-        ctx
-    );
-
-    // Process stake right away
-    self.staking_pool.process_pending_stake();
-    self.next_epoch_stake = self.next_epoch_stake + stake_amount;
-
-    staked_iota
-}
-
- - - -
- - - -## Function `request_withdraw_stake` - -Request to withdraw stake from the validator's staking pool, processed at the end of the epoch. - - -

-public(friend) fun request_withdraw_stake(self: &mut validator::Validator, staked_iota: staking_pool::StakedIota, ctx: &tx_context::TxContext): balance::Balance<iota::IOTA>
-
- - - -
-Implementation - - -

-public(package) fun request_withdraw_stake(
-    self: &mut Validator,
-    staked_iota: StakedIota,
-    ctx: &TxContext,
-) : Balance<IOTA> \{
-    let principal_amount = staked_iota.staked_iota_amount();
-    let stake_activation_epoch = staked_iota.stake_activation_epoch();
-    let withdrawn_stake = self.staking_pool.request_withdraw_stake(staked_iota, ctx);
-    let withdraw_amount = withdrawn_stake.value();
-    let reward_amount = withdraw_amount - principal_amount;
-    self.next_epoch_stake = self.next_epoch_stake - withdraw_amount;
-    event::emit(
-        UnstakingRequestEvent \{
-            pool_id: staking_pool_id(self),
-            validator_address: self.metadata.iota_address,
-            staker_address: ctx.sender(),
-            stake_activation_epoch,
-            unstaking_epoch: ctx.epoch(),
-            principal_amount,
-            reward_amount,
-        }
-    );
-    withdrawn_stake
-}
-
- - - -
- - - -## Function `request_set_gas_price` - -Request to set new gas price for the next epoch. -Need to present a -ValidatorOperationCap. - - -

-public(friend) fun request_set_gas_price(self: &mut validator::Validator, verified_cap: validator_cap::ValidatorOperationCap, new_price: u64)
-
- - - -
-Implementation - - -

-public(package) fun request_set_gas_price(
-    self: &mut Validator,
-    verified_cap: ValidatorOperationCap,
-    new_price: u64,
-) \{
-    assert!(new_price < MAX_VALIDATOR_GAS_PRICE, EGasPriceHigherThanThreshold);
-    let validator_address = *verified_cap.verified_operation_cap_address();
-    assert!(validator_address == self.metadata.iota_address, EInvalidCap);
-    self.next_epoch_gas_price = new_price;
-}
-
- - - -
- - - -## Function `set_candidate_gas_price` - -Set new gas price for the candidate validator. - - -

-public(friend) fun set_candidate_gas_price(self: &mut validator::Validator, verified_cap: validator_cap::ValidatorOperationCap, new_price: u64)
-
- - - -
-Implementation - - -

-public(package) fun set_candidate_gas_price(
-    self: &mut Validator,
-    verified_cap: ValidatorOperationCap,
-    new_price: u64
-) \{
-    assert!(is_preactive(self), ENotValidatorCandidate);
-    assert!(new_price < MAX_VALIDATOR_GAS_PRICE, EGasPriceHigherThanThreshold);
-    let validator_address = *verified_cap.verified_operation_cap_address();
-    assert!(validator_address == self.metadata.iota_address, EInvalidCap);
-    self.next_epoch_gas_price = new_price;
-    self.gas_price = new_price;
-}
-
- - - -
- - - -## Function `request_set_commission_rate` - -Request to set new commission rate for the next epoch. - - -

-public(friend) fun request_set_commission_rate(self: &mut validator::Validator, new_commission_rate: u64)
-
- - - -
-Implementation - - -

-public(package) fun request_set_commission_rate(self: &mut Validator, new_commission_rate: u64) \{
-    assert!(new_commission_rate <= MAX_COMMISSION_RATE, ECommissionRateTooHigh);
-    self.next_epoch_commission_rate = new_commission_rate;
-}
-
- - - -
- - - -## Function `set_candidate_commission_rate` - -Set new commission rate for the candidate validator. - - -

-public(friend) fun set_candidate_commission_rate(self: &mut validator::Validator, new_commission_rate: u64)
-
- - - -
-Implementation - - -

-public(package) fun set_candidate_commission_rate(self: &mut Validator, new_commission_rate: u64) \{
-    assert!(is_preactive(self), ENotValidatorCandidate);
-    assert!(new_commission_rate <= MAX_COMMISSION_RATE, ECommissionRateTooHigh);
-    self.commission_rate = new_commission_rate;
-}
-
- - - -
- - - -## Function `deposit_stake_rewards` - -Deposit stakes rewards into the validator's staking pool, called at the end of the epoch. - - -

-public(friend) fun deposit_stake_rewards(self: &mut validator::Validator, reward: balance::Balance<iota::IOTA>)
-
- - - -
-Implementation - - -

-public(package) fun deposit_stake_rewards(self: &mut Validator, reward: Balance<IOTA>) \{
-    self.next_epoch_stake = self.next_epoch_stake + reward.value();
-    self.staking_pool.deposit_rewards(reward);
-}
-
- - - -
- - - -## Function `process_pending_stakes_and_withdraws` - -Process pending stakes and withdraws, called at the end of the epoch. - - -

-public(friend) fun process_pending_stakes_and_withdraws(self: &mut validator::Validator, ctx: &tx_context::TxContext)
-
- - - -
-Implementation - - -

-public(package) fun process_pending_stakes_and_withdraws(self: &mut Validator, ctx: &TxContext) \{
-    self.staking_pool.process_pending_stakes_and_withdraws(ctx);
-    assert!(stake_amount(self) == self.next_epoch_stake, EInvalidStakeAmount);
-}
-
- - - -
- - - -## Function `is_preactive` - -Returns true if the validator is preactive. - - -

-public fun is_preactive(self: &validator::Validator): bool
-
- - - -
-Implementation - - -

-public fun is_preactive(self: &Validator): bool \{
-    self.staking_pool.is_preactive()
-}
-
- - - -
- - - -## Function `metadata` - - - -

-public fun metadata(self: &validator::Validator): &validator::ValidatorMetadata
-
- - - -
-Implementation - - -

-public fun metadata(self: &Validator): &ValidatorMetadata \{
-    &self.metadata
-}
-
- - - -
- - - -## Function `iota_address` - - - -

-public fun iota_address(self: &validator::Validator): address
-
- - - -
-Implementation - - -

-public fun iota_address(self: &Validator): address \{
-    self.metadata.iota_address
-}
-
- - - -
- - - -## Function `name` - - - -

-public fun name(self: &validator::Validator): &string::String
-
- - - -
-Implementation - - -

-public fun name(self: &Validator): &String \{
-    &self.metadata.name
-}
-
- - - -
- - - -## Function `description` - - - -

-public fun description(self: &validator::Validator): &string::String
-
- - - -
-Implementation - - -

-public fun description(self: &Validator): &String \{
-    &self.metadata.description
-}
-
- - - -
- - - -## Function `image_url` - - - -

-public fun image_url(self: &validator::Validator): &url::Url
-
- - - -
-Implementation - - -

-public fun image_url(self: &Validator): &Url \{
-    &self.metadata.image_url
-}
-
- - - -
- - - -## Function `project_url` - - - -

-public fun project_url(self: &validator::Validator): &url::Url
-
- - - -
-Implementation - - -

-public fun project_url(self: &Validator): &Url \{
-    &self.metadata.project_url
-}
-
- - - -
- - - -## Function `network_address` - - - -

-public fun network_address(self: &validator::Validator): &string::String
-
- - - -
-Implementation - - -

-public fun network_address(self: &Validator): &String \{
-    &self.metadata.net_address
-}
-
- - - -
- - - -## Function `p2p_address` - - - -

-public fun p2p_address(self: &validator::Validator): &string::String
-
- - - -
-Implementation - - -

-public fun p2p_address(self: &Validator): &String \{
-    &self.metadata.p2p_address
-}
-
- - - -
- - - -## Function `primary_address` - - - -

-public fun primary_address(self: &validator::Validator): &string::String
-
- - - -
-Implementation - - -

-public fun primary_address(self: &Validator): &String \{
-    &self.metadata.primary_address
-}
-
- - - -
- - - -## Function `worker_address` - - - -

-public fun worker_address(self: &validator::Validator): &string::String
-
- - - -
-Implementation - - -

-public fun worker_address(self: &Validator): &String \{
-    &self.metadata.worker_address
-}
-
- - - -
- - - -## Function `protocol_pubkey_bytes` - - - -

-public fun protocol_pubkey_bytes(self: &validator::Validator): &vector<u8>
-
- - - -
-Implementation - - -

-public fun protocol_pubkey_bytes(self: &Validator): &vector<u8> \{
-    &self.metadata.protocol_pubkey_bytes
-}
-
- - - -
- - - -## Function `proof_of_possession` - - - -

-public fun proof_of_possession(self: &validator::Validator): &vector<u8>
-
- - - -
-Implementation - - -

-public fun proof_of_possession(self: &Validator): &vector<u8> \{
-    &self.metadata.proof_of_possession
-}
-
- - - -
- - - -## Function `network_pubkey_bytes` - - - -

-public fun network_pubkey_bytes(self: &validator::Validator): &vector<u8>
-
- - - -
-Implementation - - -

-public fun network_pubkey_bytes(self: &Validator): &vector<u8> \{
-    &self.metadata.network_pubkey_bytes
-}
-
- - - -
- - - -## Function `worker_pubkey_bytes` - - - -

-public fun worker_pubkey_bytes(self: &validator::Validator): &vector<u8>
-
- - - -
-Implementation - - -

-public fun worker_pubkey_bytes(self: &Validator): &vector<u8> \{
-    &self.metadata.worker_pubkey_bytes
-}
-
- - - -
- - - -## Function `next_epoch_network_address` - - - -

-public fun next_epoch_network_address(self: &validator::Validator): &option::Option<string::String>
-
- - - -
-Implementation - - -

-public fun next_epoch_network_address(self: &Validator): &Option<String> \{
-    &self.metadata.next_epoch_net_address
-}
-
- - - -
- - - -## Function `next_epoch_p2p_address` - - - -

-public fun next_epoch_p2p_address(self: &validator::Validator): &option::Option<string::String>
-
- - - -
-Implementation - - -

-public fun next_epoch_p2p_address(self: &Validator): &Option<String> \{
-    &self.metadata.next_epoch_p2p_address
-}
-
- - - -
- - - -## Function `next_epoch_primary_address` - - - -

-public fun next_epoch_primary_address(self: &validator::Validator): &option::Option<string::String>
-
- - - -
-Implementation - - -

-public fun next_epoch_primary_address(self: &Validator): &Option<String> \{
-    &self.metadata.next_epoch_primary_address
-}
-
- - - -
- - - -## Function `next_epoch_worker_address` - - - -

-public fun next_epoch_worker_address(self: &validator::Validator): &option::Option<string::String>
-
- - - -
-Implementation - - -

-public fun next_epoch_worker_address(self: &Validator): &Option<String> \{
-    &self.metadata.next_epoch_worker_address
-}
-
- - - -
- - - -## Function `next_epoch_protocol_pubkey_bytes` - - - -

-public fun next_epoch_protocol_pubkey_bytes(self: &validator::Validator): &option::Option<vector<u8>>
-
- - - -
-Implementation - - -

-public fun next_epoch_protocol_pubkey_bytes(self: &Validator): &Option<vector<u8>> \{
-    &self.metadata.next_epoch_protocol_pubkey_bytes
-}
-
- - - -
- - - -## Function `next_epoch_proof_of_possession` - - - -

-public fun next_epoch_proof_of_possession(self: &validator::Validator): &option::Option<vector<u8>>
-
- - - -
-Implementation - - -

-public fun next_epoch_proof_of_possession(self: &Validator): &Option<vector<u8>> \{
-    &self.metadata.next_epoch_proof_of_possession
-}
-
- - - -
- - - -## Function `next_epoch_network_pubkey_bytes` - - - -

-public fun next_epoch_network_pubkey_bytes(self: &validator::Validator): &option::Option<vector<u8>>
-
- - - -
-Implementation - - -

-public fun next_epoch_network_pubkey_bytes(self: &Validator): &Option<vector<u8>> \{
-    &self.metadata.next_epoch_network_pubkey_bytes
-}
-
- - - -
- - - -## Function `next_epoch_worker_pubkey_bytes` - - - -

-public fun next_epoch_worker_pubkey_bytes(self: &validator::Validator): &option::Option<vector<u8>>
-
- - - -
-Implementation - - -

-public fun next_epoch_worker_pubkey_bytes(self: &Validator): &Option<vector<u8>> \{
-    &self.metadata.next_epoch_worker_pubkey_bytes
-}
-
- - - -
- - - -## Function `operation_cap_id` - - - -

-public fun operation_cap_id(self: &validator::Validator): &object::ID
-
- - - -
-Implementation - - -

-public fun operation_cap_id(self: &Validator): &ID \{
-    &self.operation_cap_id
-}
-
- - - -
- - - -## Function `next_epoch_gas_price` - - - -

-public fun next_epoch_gas_price(self: &validator::Validator): u64
-
- - - -
-Implementation - - -

-public fun next_epoch_gas_price(self: &Validator): u64 \{
-    self.next_epoch_gas_price
-}
-
- - - -
- - - -## Function `total_stake_amount` - - - -

-public fun total_stake_amount(self: &validator::Validator): u64
-
- - - -
-Implementation - - -

-public fun total_stake_amount(self: &Validator): u64 \{
-    self.staking_pool.iota_balance()
-}
-
- - - -
- - - -## Function `stake_amount` - - - -

-public fun stake_amount(self: &validator::Validator): u64
-
- - - -
-Implementation - - -

-public fun stake_amount(self: &Validator): u64 \{
-    self.staking_pool.iota_balance()
-}
-
- - - -
- - - -## Function `total_stake` - -Return the total amount staked with this validator - - -

-public fun total_stake(self: &validator::Validator): u64
-
- - - -
-Implementation - - -

-public fun total_stake(self: &Validator): u64 \{
-    stake_amount(self)
-}
-
- - - -
- - - -## Function `voting_power` - -Return the voting power of this validator. - - -

-public fun voting_power(self: &validator::Validator): u64
-
- - - -
-Implementation - - -

-public fun voting_power(self: &Validator): u64 \{
-    self.voting_power
-}
-
- - - -
- - - -## Function `set_voting_power` - -Set the voting power of this validator, called only from validator_set. - - -

-public(friend) fun set_voting_power(self: &mut validator::Validator, new_voting_power: u64)
-
- - - -
-Implementation - - -

-public(package) fun set_voting_power(self: &mut Validator, new_voting_power: u64) \{
-    self.voting_power = new_voting_power;
-}
-
- - - -
- - - -## Function `pending_stake_amount` - - - -

-public fun pending_stake_amount(self: &validator::Validator): u64
-
- - - -
-Implementation - - -

-public fun pending_stake_amount(self: &Validator): u64 \{
-    self.staking_pool.pending_stake_amount()
-}
-
- - - -
- - - -## Function `pending_stake_withdraw_amount` - - - -

-public fun pending_stake_withdraw_amount(self: &validator::Validator): u64
-
- - - -
-Implementation - - -

-public fun pending_stake_withdraw_amount(self: &Validator): u64 \{
-    self.staking_pool.pending_stake_withdraw_amount()
-}
-
- - - -
- - - -## Function `gas_price` - - - -

-public fun gas_price(self: &validator::Validator): u64
-
- - - -
-Implementation - - -

-public fun gas_price(self: &Validator): u64 \{
-    self.gas_price
-}
-
- - - -
- - - -## Function `commission_rate` - - - -

-public fun commission_rate(self: &validator::Validator): u64
-
- - - -
-Implementation - - -

-public fun commission_rate(self: &Validator): u64 \{
-    self.commission_rate
-}
-
- - - -
- - - -## Function `pool_token_exchange_rate_at_epoch` - - - -

-public fun pool_token_exchange_rate_at_epoch(self: &validator::Validator, epoch: u64): staking_pool::PoolTokenExchangeRate
-
- - - -
-Implementation - - -

-public fun pool_token_exchange_rate_at_epoch(self: &Validator, epoch: u64): PoolTokenExchangeRate \{
-    self.staking_pool.pool_token_exchange_rate_at_epoch(epoch)
-}
-
- - - -
- - - -## Function `staking_pool_id` - - - -

-public fun staking_pool_id(self: &validator::Validator): object::ID
-
- - - -
-Implementation - - -

-public fun staking_pool_id(self: &Validator): ID \{
-    object::id(&self.staking_pool)
-}
-
- - - -
- - - -## Function `is_duplicate` - - - -

-public fun is_duplicate(self: &validator::Validator, other: &validator::Validator): bool
-
- - - -
-Implementation - - -

-public fun is_duplicate(self: &Validator, other: &Validator): bool \{
-     self.metadata.iota_address == other.metadata.iota_address
-        || self.metadata.name == other.metadata.name
-        || self.metadata.net_address == other.metadata.net_address
-        || self.metadata.p2p_address == other.metadata.p2p_address
-        || self.metadata.protocol_pubkey_bytes == other.metadata.protocol_pubkey_bytes
-        || self.metadata.network_pubkey_bytes == other.metadata.network_pubkey_bytes
-        || self.metadata.network_pubkey_bytes == other.metadata.worker_pubkey_bytes
-        || self.metadata.worker_pubkey_bytes == other.metadata.worker_pubkey_bytes
-        || self.metadata.worker_pubkey_bytes == other.metadata.network_pubkey_bytes
-        // All next epoch parameters.
-        || is_equal_some(&self.metadata.next_epoch_net_address, &other.metadata.next_epoch_net_address)
-        || is_equal_some(&self.metadata.next_epoch_p2p_address, &other.metadata.next_epoch_p2p_address)
-        || is_equal_some(&self.metadata.next_epoch_protocol_pubkey_bytes, &other.metadata.next_epoch_protocol_pubkey_bytes)
-        || is_equal_some(&self.metadata.next_epoch_network_pubkey_bytes, &other.metadata.next_epoch_network_pubkey_bytes)
-        || is_equal_some(&self.metadata.next_epoch_network_pubkey_bytes, &other.metadata.next_epoch_worker_pubkey_bytes)
-        || is_equal_some(&self.metadata.next_epoch_worker_pubkey_bytes, &other.metadata.next_epoch_worker_pubkey_bytes)
-        || is_equal_some(&self.metadata.next_epoch_worker_pubkey_bytes, &other.metadata.next_epoch_network_pubkey_bytes)
-        // My next epoch parameters with other current epoch parameters.
-        || is_equal_some_and_value(&self.metadata.next_epoch_net_address, &other.metadata.net_address)
-        || is_equal_some_and_value(&self.metadata.next_epoch_p2p_address, &other.metadata.p2p_address)
-        || is_equal_some_and_value(&self.metadata.next_epoch_protocol_pubkey_bytes, &other.metadata.protocol_pubkey_bytes)
-        || is_equal_some_and_value(&self.metadata.next_epoch_network_pubkey_bytes, &other.metadata.network_pubkey_bytes)
-        || is_equal_some_and_value(&self.metadata.next_epoch_network_pubkey_bytes, &other.metadata.worker_pubkey_bytes)
-        || is_equal_some_and_value(&self.metadata.next_epoch_worker_pubkey_bytes, &other.metadata.worker_pubkey_bytes)
-        || is_equal_some_and_value(&self.metadata.next_epoch_worker_pubkey_bytes, &other.metadata.network_pubkey_bytes)
-        // Other next epoch parameters with my current epoch parameters.
-        || is_equal_some_and_value(&other.metadata.next_epoch_net_address, &self.metadata.net_address)
-        || is_equal_some_and_value(&other.metadata.next_epoch_p2p_address, &self.metadata.p2p_address)
-        || is_equal_some_and_value(&other.metadata.next_epoch_protocol_pubkey_bytes, &self.metadata.protocol_pubkey_bytes)
-        || is_equal_some_and_value(&other.metadata.next_epoch_network_pubkey_bytes, &self.metadata.network_pubkey_bytes)
-        || is_equal_some_and_value(&other.metadata.next_epoch_network_pubkey_bytes, &self.metadata.worker_pubkey_bytes)
-        || is_equal_some_and_value(&other.metadata.next_epoch_worker_pubkey_bytes, &self.metadata.worker_pubkey_bytes)
-        || is_equal_some_and_value(&other.metadata.next_epoch_worker_pubkey_bytes, &self.metadata.network_pubkey_bytes)
-}
-
- - - -
- - - -## Function `is_equal_some_and_value` - - - -

-fun is_equal_some_and_value<T>(a: &option::Option<T>, b: &T): bool
-
- - - -
-Implementation - - -

-fun is_equal_some_and_value<T>(a: &Option<T>, b: &T): bool \{
-    if (a.is_none()) \{
-        false
-    } else \{
-        a.borrow() == b
-    }
-}
-
- - - -
- - - -## Function `is_equal_some` - - - -

-fun is_equal_some<T>(a: &option::Option<T>, b: &option::Option<T>): bool
-
- - - -
-Implementation - - -

-fun is_equal_some<T>(a: &Option<T>, b: &Option<T>): bool \{
-    if (a.is_none() || b.is_none()) \{
-        false
-    } else \{
-        a.borrow() == b.borrow()
-    }
-}
-
- - - -
- - - -## Function `new_unverified_validator_operation_cap_and_transfer` - -Create a new -UnverifiedValidatorOperationCap, transfer to the validator, -and registers it, thus revoking the previous cap's permission. - - -

-public(friend) fun new_unverified_validator_operation_cap_and_transfer(self: &mut validator::Validator, ctx: &mut tx_context::TxContext)
-
- - - -
-Implementation - - -

-public(package) fun new_unverified_validator_operation_cap_and_transfer(self: &mut Validator, ctx: &mut TxContext) \{
-    let address = ctx.sender();
-    assert!(address == self.metadata.iota_address, ENewCapNotCreatedByValidatorItself);
-    let new_id = validator_cap::new_unverified_validator_operation_cap_and_transfer(address, ctx);
-    self.operation_cap_id = new_id;
-}
-
- - - -
- - - -## Function `update_name` - -Update name of the validator. - - -

-public(friend) fun update_name(self: &mut validator::Validator, name: vector<u8>)
-
- - - -
-Implementation - - -

-public(package) fun update_name(self: &mut Validator, name: vector<u8>) \{
-    assert!(
-        name.length() <= MAX_VALIDATOR_METADATA_LENGTH,
-        EValidatorMetadataExceedingLengthLimit
-    );
-    self.metadata.name = name.to_ascii_string().to_string();
-}
-
- - - -
- - - -## Function `update_description` - -Update description of the validator. - - -

-public(friend) fun update_description(self: &mut validator::Validator, description: vector<u8>)
-
- - - -
-Implementation - - -

-public(package) fun update_description(self: &mut Validator, description: vector<u8>) \{
-    assert!(
-        description.length() <= MAX_VALIDATOR_METADATA_LENGTH,
-        EValidatorMetadataExceedingLengthLimit
-    );
-    self.metadata.description = description.to_ascii_string().to_string();
-}
-
- - - -
- - - -## Function `update_image_url` - -Update image url of the validator. - - -

-public(friend) fun update_image_url(self: &mut validator::Validator, image_url: vector<u8>)
-
- - - -
-Implementation - - -

-public(package) fun update_image_url(self: &mut Validator, image_url: vector<u8>) \{
-    assert!(
-        image_url.length() <= MAX_VALIDATOR_METADATA_LENGTH,
-        EValidatorMetadataExceedingLengthLimit
-    );
-    self.metadata.image_url = url::new_unsafe_from_bytes(image_url);
-}
-
- - - -
- - - -## Function `update_project_url` - -Update project url of the validator. - - -

-public(friend) fun update_project_url(self: &mut validator::Validator, project_url: vector<u8>)
-
- - - -
-Implementation - - -

-public(package) fun update_project_url(self: &mut Validator, project_url: vector<u8>) \{
-    assert!(
-        project_url.length() <= MAX_VALIDATOR_METADATA_LENGTH,
-        EValidatorMetadataExceedingLengthLimit
-    );
-    self.metadata.project_url = url::new_unsafe_from_bytes(project_url);
-}
-
- - - -
- - - -## Function `update_next_epoch_network_address` - -Update network address of this validator, taking effects from next epoch - - -

-public(friend) fun update_next_epoch_network_address(self: &mut validator::Validator, net_address: vector<u8>)
-
- - - -
-Implementation - - -

-public(package) fun update_next_epoch_network_address(self: &mut Validator, net_address: vector<u8>) \{
-    assert!(
-        net_address.length() <= MAX_VALIDATOR_METADATA_LENGTH,
-        EValidatorMetadataExceedingLengthLimit
-    );
-    let net_address = net_address.to_ascii_string().to_string();
-    self.metadata.next_epoch_net_address = option::some(net_address);
-    validate_metadata(&self.metadata);
-}
-
- - - -
- - - -## Function `update_candidate_network_address` - -Update network address of this candidate validator - - -

-public(friend) fun update_candidate_network_address(self: &mut validator::Validator, net_address: vector<u8>)
-
- - - -
-Implementation - - -

-public(package) fun update_candidate_network_address(self: &mut Validator, net_address: vector<u8>) \{
-    assert!(is_preactive(self), ENotValidatorCandidate);
-    assert!(
-        net_address.length() <= MAX_VALIDATOR_METADATA_LENGTH,
-        EValidatorMetadataExceedingLengthLimit
-    );
-    let net_address = net_address.to_ascii_string().to_string();
-    self.metadata.net_address = net_address;
-    validate_metadata(&self.metadata);
-}
-
- - - -
- - - -## Function `update_next_epoch_p2p_address` - -Update p2p address of this validator, taking effects from next epoch - - -

-public(friend) fun update_next_epoch_p2p_address(self: &mut validator::Validator, p2p_address: vector<u8>)
-
- - - -
-Implementation - - -

-public(package) fun update_next_epoch_p2p_address(self: &mut Validator, p2p_address: vector<u8>) \{
-    assert!(
-        p2p_address.length() <= MAX_VALIDATOR_METADATA_LENGTH,
-        EValidatorMetadataExceedingLengthLimit
-    );
-    let p2p_address = p2p_address.to_ascii_string().to_string();
-    self.metadata.next_epoch_p2p_address = option::some(p2p_address);
-    validate_metadata(&self.metadata);
-}
-
- - - -
- - - -## Function `update_candidate_p2p_address` - -Update p2p address of this candidate validator - - -

-public(friend) fun update_candidate_p2p_address(self: &mut validator::Validator, p2p_address: vector<u8>)
-
- - - -
-Implementation - - -

-public(package) fun update_candidate_p2p_address(self: &mut Validator, p2p_address: vector<u8>) \{
-    assert!(is_preactive(self), ENotValidatorCandidate);
-    assert!(
-        p2p_address.length() <= MAX_VALIDATOR_METADATA_LENGTH,
-        EValidatorMetadataExceedingLengthLimit
-    );
-    let p2p_address = p2p_address.to_ascii_string().to_string();
-    self.metadata.p2p_address = p2p_address;
-    validate_metadata(&self.metadata);
-}
-
- - - -
- - - -## Function `update_next_epoch_primary_address` - -Update primary address of this validator, taking effects from next epoch - - -

-public(friend) fun update_next_epoch_primary_address(self: &mut validator::Validator, primary_address: vector<u8>)
-
- - - -
-Implementation - - -

-public(package) fun update_next_epoch_primary_address(self: &mut Validator, primary_address: vector<u8>) \{
-    assert!(
-        primary_address.length() <= MAX_VALIDATOR_METADATA_LENGTH,
-        EValidatorMetadataExceedingLengthLimit
-    );
-    let primary_address = primary_address.to_ascii_string().to_string();
-    self.metadata.next_epoch_primary_address = option::some(primary_address);
-    validate_metadata(&self.metadata);
-}
-
- - - -
- - - -## Function `update_candidate_primary_address` - -Update primary address of this candidate validator - - -

-public(friend) fun update_candidate_primary_address(self: &mut validator::Validator, primary_address: vector<u8>)
-
- - - -
-Implementation - - -

-public(package) fun update_candidate_primary_address(self: &mut Validator, primary_address: vector<u8>) \{
-    assert!(is_preactive(self), ENotValidatorCandidate);
-    assert!(
-        primary_address.length() <= MAX_VALIDATOR_METADATA_LENGTH,
-        EValidatorMetadataExceedingLengthLimit
-    );
-    let primary_address = primary_address.to_ascii_string().to_string();
-    self.metadata.primary_address = primary_address;
-    validate_metadata(&self.metadata);
-}
-
- - - -
- - - -## Function `update_next_epoch_worker_address` - -Update worker address of this validator, taking effects from next epoch - - -

-public(friend) fun update_next_epoch_worker_address(self: &mut validator::Validator, worker_address: vector<u8>)
-
- - - -
-Implementation - - -

-public(package) fun update_next_epoch_worker_address(self: &mut Validator, worker_address: vector<u8>) \{
-    assert!(
-        worker_address.length() <= MAX_VALIDATOR_METADATA_LENGTH,
-        EValidatorMetadataExceedingLengthLimit
-    );
-    let worker_address = worker_address.to_ascii_string().to_string();
-    self.metadata.next_epoch_worker_address = option::some(worker_address);
-    validate_metadata(&self.metadata);
-}
-
- - - -
- - - -## Function `update_candidate_worker_address` - -Update worker address of this candidate validator - - -

-public(friend) fun update_candidate_worker_address(self: &mut validator::Validator, worker_address: vector<u8>)
-
- - - -
-Implementation - - -

-public(package) fun update_candidate_worker_address(self: &mut Validator, worker_address: vector<u8>) \{
-    assert!(is_preactive(self), ENotValidatorCandidate);
-    assert!(
-        worker_address.length() <= MAX_VALIDATOR_METADATA_LENGTH,
-        EValidatorMetadataExceedingLengthLimit
-    );
-    let worker_address = worker_address.to_ascii_string().to_string();
-    self.metadata.worker_address = worker_address;
-    validate_metadata(&self.metadata);
-}
-
- - - -
- - - -## Function `update_next_epoch_protocol_pubkey` - -Update protocol public key of this validator, taking effects from next epoch - - -

-public(friend) fun update_next_epoch_protocol_pubkey(self: &mut validator::Validator, protocol_pubkey: vector<u8>, proof_of_possession: vector<u8>)
-
- - - -
-Implementation - - -

-public(package) fun update_next_epoch_protocol_pubkey(self: &mut Validator, protocol_pubkey: vector<u8>, proof_of_possession: vector<u8>) \{
-    self.metadata.next_epoch_protocol_pubkey_bytes = option::some(protocol_pubkey);
-    self.metadata.next_epoch_proof_of_possession = option::some(proof_of_possession);
-    validate_metadata(&self.metadata);
-}
-
- - - -
- - - -## Function `update_candidate_protocol_pubkey` - -Update protocol public key of this candidate validator - - -

-public(friend) fun update_candidate_protocol_pubkey(self: &mut validator::Validator, protocol_pubkey: vector<u8>, proof_of_possession: vector<u8>)
-
- - - -
-Implementation - - -

-public(package) fun update_candidate_protocol_pubkey(self: &mut Validator, protocol_pubkey: vector<u8>, proof_of_possession: vector<u8>) \{
-    assert!(is_preactive(self), ENotValidatorCandidate);
-    self.metadata.protocol_pubkey_bytes = protocol_pubkey;
-    self.metadata.proof_of_possession = proof_of_possession;
-    validate_metadata(&self.metadata);
-}
-
- - - -
- - - -## Function `update_next_epoch_network_pubkey` - -Update network public key of this validator, taking effects from next epoch - - -

-public(friend) fun update_next_epoch_network_pubkey(self: &mut validator::Validator, network_pubkey: vector<u8>)
-
- - - -
-Implementation - - -

-public(package) fun update_next_epoch_network_pubkey(self: &mut Validator, network_pubkey: vector<u8>) \{
-    self.metadata.next_epoch_network_pubkey_bytes = option::some(network_pubkey);
-    validate_metadata(&self.metadata);
-}
-
- - - -
- - - -## Function `update_candidate_network_pubkey` - -Update network public key of this candidate validator - - -

-public(friend) fun update_candidate_network_pubkey(self: &mut validator::Validator, network_pubkey: vector<u8>)
-
- - - -
-Implementation - - -

-public(package) fun update_candidate_network_pubkey(self: &mut Validator, network_pubkey: vector<u8>) \{
-    assert!(is_preactive(self), ENotValidatorCandidate);
-    self.metadata.network_pubkey_bytes = network_pubkey;
-    validate_metadata(&self.metadata);
-}
-
- - - -
- - - -## Function `update_next_epoch_worker_pubkey` - -Update Narwhal worker public key of this validator, taking effects from next epoch - - -

-public(friend) fun update_next_epoch_worker_pubkey(self: &mut validator::Validator, worker_pubkey: vector<u8>)
-
- - - -
-Implementation - - -

-public(package) fun update_next_epoch_worker_pubkey(self: &mut Validator, worker_pubkey: vector<u8>) \{
-    self.metadata.next_epoch_worker_pubkey_bytes = option::some(worker_pubkey);
-    validate_metadata(&self.metadata);
-}
-
- - - -
- - - -## Function `update_candidate_worker_pubkey` - -Update Narwhal worker public key of this candidate validator - - -

-public(friend) fun update_candidate_worker_pubkey(self: &mut validator::Validator, worker_pubkey: vector<u8>)
-
- - - -
-Implementation - - -

-public(package) fun update_candidate_worker_pubkey(self: &mut Validator, worker_pubkey: vector<u8>) \{
-    assert!(is_preactive(self), ENotValidatorCandidate);
-    self.metadata.worker_pubkey_bytes = worker_pubkey;
-    validate_metadata(&self.metadata);
-}
-
- - - -
- - - -## Function `effectuate_staged_metadata` - -Effectutate all staged next epoch metadata for this validator. -NOTE: this function SHOULD ONLY be called by validator_set when -advancing an epoch. - - -

-public(friend) fun effectuate_staged_metadata(self: &mut validator::Validator)
-
- - - -
-Implementation - - -

-public(package) fun effectuate_staged_metadata(self: &mut Validator) \{
-    if (next_epoch_network_address(self).is_some()) \{
-        self.metadata.net_address = self.metadata.next_epoch_net_address.extract();
-        self.metadata.next_epoch_net_address = option::none();
-    };
-
-    if (next_epoch_p2p_address(self).is_some()) \{
-        self.metadata.p2p_address = self.metadata.next_epoch_p2p_address.extract();
-        self.metadata.next_epoch_p2p_address = option::none();
-    };
-
-    if (next_epoch_primary_address(self).is_some()) \{
-        self.metadata.primary_address = self.metadata.next_epoch_primary_address.extract();
-        self.metadata.next_epoch_primary_address = option::none();
-    };
-
-    if (next_epoch_worker_address(self).is_some()) \{
-        self.metadata.worker_address = self.metadata.next_epoch_worker_address.extract();
-        self.metadata.next_epoch_worker_address = option::none();
-    };
-
-    if (next_epoch_protocol_pubkey_bytes(self).is_some()) \{
-        self.metadata.protocol_pubkey_bytes = self.metadata.next_epoch_protocol_pubkey_bytes.extract();
-        self.metadata.next_epoch_protocol_pubkey_bytes = option::none();
-        self.metadata.proof_of_possession = self.metadata.next_epoch_proof_of_possession.extract();
-        self.metadata.next_epoch_proof_of_possession = option::none();
-    };
-
-    if (next_epoch_network_pubkey_bytes(self).is_some()) \{
-        self.metadata.network_pubkey_bytes = self.metadata.next_epoch_network_pubkey_bytes.extract();
-        self.metadata.next_epoch_network_pubkey_bytes = option::none();
-    };
-
-    if (next_epoch_worker_pubkey_bytes(self).is_some()) \{
-        self.metadata.worker_pubkey_bytes = self.metadata.next_epoch_worker_pubkey_bytes.extract();
-        self.metadata.next_epoch_worker_pubkey_bytes = option::none();
-    };
-}
-
- - - -
- - - -## Function `validate_metadata` - -Aborts if validator metadata is valid - - -

-public fun validate_metadata(metadata: &validator::ValidatorMetadata)
-
- - - -
-Implementation - - -

-public fun validate_metadata(metadata: &ValidatorMetadata) \{
-    validate_metadata_bcs(bcs::to_bytes(metadata));
-}
-
- - - -
- - - -## Function `validate_metadata_bcs` - - - -

-public fun validate_metadata_bcs(metadata: vector<u8>)
-
- - - -
-Implementation - - -

-public native fun validate_metadata_bcs(metadata: vector<u8>);
-
- - - -
- - - -## Function `get_staking_pool_ref` - - - -

-public(friend) fun get_staking_pool_ref(self: &validator::Validator): &staking_pool::StakingPool
-
- - - -
-Implementation - - -

-public(package) fun get_staking_pool_ref(self: &Validator) : &StakingPool \{
-    &self.staking_pool
-}
-
- - - -
- - - -## Function `new_from_metadata` - -Create a new validator from the given -ValidatorMetadata, called by both -new and -new_for_testing. - - -

-fun new_from_metadata(metadata: validator::ValidatorMetadata, gas_price: u64, commission_rate: u64, ctx: &mut tx_context::TxContext): validator::Validator
-
- - - -
-Implementation - - -

-fun new_from_metadata(
-    metadata: ValidatorMetadata,
-    gas_price: u64,
-    commission_rate: u64,
-    ctx: &mut TxContext
-): Validator \{
-    let iota_address = metadata.iota_address;
-
-    let staking_pool = staking_pool::new(ctx);
-
-    let operation_cap_id = validator_cap::new_unverified_validator_operation_cap_and_transfer(iota_address, ctx);
-    Validator \{
-        metadata,
-        // Initialize the voting power to be 0.
-        // At the epoch change where this validator is actually added to the
-        // active validator set, the voting power will be updated accordingly.
-        voting_power: 0,
-        operation_cap_id,
-        gas_price,
-        staking_pool,
-        commission_rate,
-        next_epoch_stake: 0,
-        next_epoch_gas_price: gas_price,
-        next_epoch_commission_rate: commission_rate,
-        extra_fields: bag::new(ctx),
-    }
-}
-
- - - -
diff --git a/crates/iota-framework/docs/iota-system/validator_cap.mdx b/crates/iota-framework/docs/iota-system/validator_cap.mdx deleted file mode 100644 index 0cb49b7dd7a..00000000000 --- a/crates/iota-framework/docs/iota-system/validator_cap.mdx +++ /dev/null @@ -1,238 +0,0 @@ ---- -title: Module `0x3::validator_cap` ---- -import Link from '@docusaurus/Link'; - - - - -- [Resource `UnverifiedValidatorOperationCap`](#0x3_validator_cap_UnverifiedValidatorOperationCap) -- [Struct `ValidatorOperationCap`](#0x3_validator_cap_ValidatorOperationCap) -- [Function `unverified_operation_cap_address`](#0x3_validator_cap_unverified_operation_cap_address) -- [Function `verified_operation_cap_address`](#0x3_validator_cap_verified_operation_cap_address) -- [Function `new_unverified_validator_operation_cap_and_transfer`](#0x3_validator_cap_new_unverified_validator_operation_cap_and_transfer) -- [Function `new_from_unverified`](#0x3_validator_cap_new_from_unverified) - - -

-use 0x2::object;
-use 0x2::transfer;
-use 0x2::tx_context;
-
- - - - - -## Resource `UnverifiedValidatorOperationCap` - -The capability object is created when creating a new -Validator or when the -validator explicitly creates a new capability object for rotation/revocation. -The holder address of this object can perform some validator operations on behalf of -the authorizer validator. Thus, if a validator wants to separate the keys for operation -(such as reference gas price setting or tallying rule reporting) from fund/staking, it -could transfer this capability object to another address. -To facilitate rotating/revocation, -Validator stores the ID of currently valid - -UnverifiedValidatorOperationCap. Thus, before converting -UnverifiedValidatorOperationCap -to -ValidatorOperationCap, verification needs to be done to make sure -the cap object is still valid. - - -

-struct UnverifiedValidatorOperationCap has store, key
-
- - - -
-Fields - - -
-
- -id: object::UID -
-
- -
-
- -authorizer_validator_address: address -
-
- -
-
- - -
- - - -## Struct `ValidatorOperationCap` - -Privileged operations require -ValidatorOperationCap for permission check. -This is only constructed after successful verification. - - -

-struct ValidatorOperationCap has drop
-
- - - -
-Fields - - -
-
- -authorizer_validator_address: address -
-
- -
-
- - -
- - - -## Function `unverified_operation_cap_address` - - - -

-public(friend) fun unverified_operation_cap_address(cap: &validator_cap::UnverifiedValidatorOperationCap): &address
-
- - - -
-Implementation - - -

-public(package) fun unverified_operation_cap_address(cap: &UnverifiedValidatorOperationCap): &address \{
-    &cap.authorizer_validator_address
-}
-
- - - -
- - - -## Function `verified_operation_cap_address` - - - -

-public(friend) fun verified_operation_cap_address(cap: &validator_cap::ValidatorOperationCap): &address
-
- - - -
-Implementation - - -

-public(package) fun verified_operation_cap_address(cap: &ValidatorOperationCap): &address \{
-    &cap.authorizer_validator_address
-}
-
- - - -
- - - -## Function `new_unverified_validator_operation_cap_and_transfer` - -Should be only called by the friend modules when adding a -Validator -or rotating an existing validaotr's -operation_cap_id. - - -

-public(friend) fun new_unverified_validator_operation_cap_and_transfer(validator_address: address, ctx: &mut tx_context::TxContext): object::ID
-
- - - -
-Implementation - - -

-public(package) fun new_unverified_validator_operation_cap_and_transfer(
-    validator_address: address,
-    ctx: &mut TxContext,
-): ID \{
-    // This function needs to be called only by the validator itself, except
-    // 1. in genesis where all valdiators are created by @0x0
-    // 2. in tests where @0x0 could be used to simplify the setup
-    let sender_address = ctx.sender();
-    assert!(sender_address == @0x0 || sender_address == validator_address, 0);
-
-    let operation_cap = UnverifiedValidatorOperationCap \{
-        id: object::new(ctx),
-        authorizer_validator_address: validator_address,
-    };
-    let operation_cap_id = object::id(&operation_cap);
-    transfer::public_transfer(operation_cap, validator_address);
-    operation_cap_id
-}
-
- - - -
- - - -## Function `new_from_unverified` - -Convert an -UnverifiedValidatorOperationCap to -ValidatorOperationCap. -Should only be called by -validator_set module AFTER verification. - - -

-public(friend) fun new_from_unverified(cap: &validator_cap::UnverifiedValidatorOperationCap): validator_cap::ValidatorOperationCap
-
- - - -
-Implementation - - -

-public(package) fun new_from_unverified(
-    cap: &UnverifiedValidatorOperationCap,
-): ValidatorOperationCap \{
-    ValidatorOperationCap \{
-        authorizer_validator_address: cap.authorizer_validator_address
-    }
-}
-
- - - -
diff --git a/crates/iota-framework/docs/iota-system/validator_set.mdx b/crates/iota-framework/docs/iota-system/validator_set.mdx deleted file mode 100644 index 661f19a9d41..00000000000 --- a/crates/iota-framework/docs/iota-system/validator_set.mdx +++ /dev/null @@ -1,3037 +0,0 @@ ---- -title: Module `0x3::validator_set` ---- -import Link from '@docusaurus/Link'; - - - - -- [Struct `ValidatorSet`](#0x3_validator_set_ValidatorSet) -- [Struct `ValidatorEpochInfoEvent`](#0x3_validator_set_ValidatorEpochInfoEvent) -- [Struct `ValidatorEpochInfoEventV2`](#0x3_validator_set_ValidatorEpochInfoEventV2) -- [Struct `ValidatorJoinEvent`](#0x3_validator_set_ValidatorJoinEvent) -- [Struct `ValidatorLeaveEvent`](#0x3_validator_set_ValidatorLeaveEvent) -- [Constants](#@Constants_0) -- [Function `new`](#0x3_validator_set_new) -- [Function `request_add_validator_candidate`](#0x3_validator_set_request_add_validator_candidate) -- [Function `request_remove_validator_candidate`](#0x3_validator_set_request_remove_validator_candidate) -- [Function `request_add_validator`](#0x3_validator_set_request_add_validator) -- [Function `assert_no_pending_or_active_duplicates`](#0x3_validator_set_assert_no_pending_or_active_duplicates) -- [Function `request_remove_validator`](#0x3_validator_set_request_remove_validator) -- [Function `request_add_stake`](#0x3_validator_set_request_add_stake) -- [Function `request_withdraw_stake`](#0x3_validator_set_request_withdraw_stake) -- [Function `request_set_commission_rate`](#0x3_validator_set_request_set_commission_rate) -- [Function `advance_epoch`](#0x3_validator_set_advance_epoch) -- [Function `update_and_process_low_stake_departures`](#0x3_validator_set_update_and_process_low_stake_departures) -- [Function `effectuate_staged_metadata`](#0x3_validator_set_effectuate_staged_metadata) -- [Function `derive_reference_gas_price`](#0x3_validator_set_derive_reference_gas_price) -- [Function `total_stake`](#0x3_validator_set_total_stake) -- [Function `validator_total_stake_amount`](#0x3_validator_set_validator_total_stake_amount) -- [Function `validator_stake_amount`](#0x3_validator_set_validator_stake_amount) -- [Function `validator_staking_pool_id`](#0x3_validator_set_validator_staking_pool_id) -- [Function `staking_pool_mappings`](#0x3_validator_set_staking_pool_mappings) -- [Function `pool_exchange_rates`](#0x3_validator_set_pool_exchange_rates) -- [Function `next_epoch_validator_count`](#0x3_validator_set_next_epoch_validator_count) -- [Function `is_active_validator_by_iota_address`](#0x3_validator_set_is_active_validator_by_iota_address) -- [Function `is_duplicate_with_active_validator`](#0x3_validator_set_is_duplicate_with_active_validator) -- [Function `is_duplicate_validator`](#0x3_validator_set_is_duplicate_validator) -- [Function `count_duplicates_vec`](#0x3_validator_set_count_duplicates_vec) -- [Function `is_duplicate_with_pending_validator`](#0x3_validator_set_is_duplicate_with_pending_validator) -- [Function `count_duplicates_tablevec`](#0x3_validator_set_count_duplicates_tablevec) -- [Function `get_candidate_or_active_validator_mut`](#0x3_validator_set_get_candidate_or_active_validator_mut) -- [Function `find_validator`](#0x3_validator_set_find_validator) -- [Function `find_validator_from_table_vec`](#0x3_validator_set_find_validator_from_table_vec) -- [Function `get_validator_indices`](#0x3_validator_set_get_validator_indices) -- [Function `get_validator_mut`](#0x3_validator_set_get_validator_mut) -- [Function `get_active_or_pending_or_candidate_validator_mut`](#0x3_validator_set_get_active_or_pending_or_candidate_validator_mut) -- [Function `get_validator_mut_with_verified_cap`](#0x3_validator_set_get_validator_mut_with_verified_cap) -- [Function `get_validator_mut_with_ctx`](#0x3_validator_set_get_validator_mut_with_ctx) -- [Function `get_validator_mut_with_ctx_including_candidates`](#0x3_validator_set_get_validator_mut_with_ctx_including_candidates) -- [Function `get_validator_ref`](#0x3_validator_set_get_validator_ref) -- [Function `get_active_or_pending_or_candidate_validator_ref`](#0x3_validator_set_get_active_or_pending_or_candidate_validator_ref) -- [Function `get_active_validator_ref`](#0x3_validator_set_get_active_validator_ref) -- [Function `get_pending_validator_ref`](#0x3_validator_set_get_pending_validator_ref) -- [Function `verify_cap`](#0x3_validator_set_verify_cap) -- [Function `process_pending_removals`](#0x3_validator_set_process_pending_removals) -- [Function `process_validator_departure`](#0x3_validator_set_process_validator_departure) -- [Function `clean_report_records_leaving_validator`](#0x3_validator_set_clean_report_records_leaving_validator) -- [Function `process_pending_validators`](#0x3_validator_set_process_pending_validators) -- [Function `sort_removal_list`](#0x3_validator_set_sort_removal_list) -- [Function `process_pending_stakes_and_withdraws`](#0x3_validator_set_process_pending_stakes_and_withdraws) -- [Function `calculate_total_stakes`](#0x3_validator_set_calculate_total_stakes) -- [Function `adjust_stake_and_gas_price`](#0x3_validator_set_adjust_stake_and_gas_price) -- [Function `compute_reward_adjustments`](#0x3_validator_set_compute_reward_adjustments) -- [Function `compute_slashed_validators`](#0x3_validator_set_compute_slashed_validators) -- [Function `compute_unadjusted_reward_distribution`](#0x3_validator_set_compute_unadjusted_reward_distribution) -- [Function `compute_adjusted_reward_distribution`](#0x3_validator_set_compute_adjusted_reward_distribution) -- [Function `distribute_reward`](#0x3_validator_set_distribute_reward) -- [Function `emit_validator_epoch_events`](#0x3_validator_set_emit_validator_epoch_events) -- [Function `sum_voting_power_by_addresses`](#0x3_validator_set_sum_voting_power_by_addresses) -- [Function `active_validators`](#0x3_validator_set_active_validators) -- [Function `is_validator_candidate`](#0x3_validator_set_is_validator_candidate) -- [Function `is_inactive_validator`](#0x3_validator_set_is_inactive_validator) -- [Function `active_validator_addresses`](#0x3_validator_set_active_validator_addresses) - - -

-use 0x1::option;
-use 0x1::vector;
-use 0x2::bag;
-use 0x2::balance;
-use 0x2::event;
-use 0x2::iota;
-use 0x2::object;
-use 0x2::priority_queue;
-use 0x2::table;
-use 0x2::table_vec;
-use 0x2::transfer;
-use 0x2::tx_context;
-use 0x2::vec_map;
-use 0x2::vec_set;
-use 0x3::staking_pool;
-use 0x3::validator;
-use 0x3::validator_cap;
-use 0x3::validator_wrapper;
-use 0x3::voting_power;
-
- - - - - -## Struct `ValidatorSet` - - - -

-struct ValidatorSet has store
-
- - - -
-Fields - - -
-
- -total_stake: u64 -
-
- Total amount of stake from all active validators at the beginning of the epoch. -
-
- -active_validators: vector<validator::Validator> -
-
- The current list of active validators. -
-
- -pending_active_validators: table_vec::TableVec<validator::Validator> -
-
- List of new validator candidates added during the current epoch. - They will be processed at the end of the epoch. -
-
- -pending_removals: vector<u64> -
-
- Removal requests from the validators. Each element is an index - pointing to -active_validators. -
-
- -staking_pool_mappings: table::Table<object::ID, address> -
-
- Mappings from staking pool's ID to the iota address of a validator. -
-
- -inactive_validators: table::Table<object::ID, validator_wrapper::ValidatorWrapper> -
-
- Mapping from a staking pool ID to the inactive validator that has that pool as its staking pool. - When a validator is deactivated the validator is removed from -active_validators it - is added to this table so that stakers can continue to withdraw their stake from it. -
-
- -validator_candidates: table::Table<address, validator_wrapper::ValidatorWrapper> -
-
- Table storing preactive/candidate validators, mapping their addresses to their -Validator structs. - When an address calls -request_add_validator_candidate, they get added to this table and become a preactive - validator. - When the candidate has met the min stake requirement, they can call -request_add_validator to - officially add them to the active validator set -active_validators next epoch. -
-
- -at_risk_validators: vec_map::VecMap<address, u64> -
-
- Table storing the number of epochs during which a validator's stake has been below the low stake threshold. -
-
- -extra_fields: bag::Bag -
-
- Any extra fields that's not defined statically. -
-
- - -
- - - -## Struct `ValidatorEpochInfoEvent` - -Event containing staking and rewards related information of -each validator, emitted during epoch advancement. - - -

-struct ValidatorEpochInfoEvent has copy, drop
-
- - - -
-Fields - - -
-
- -epoch: u64 -
-
- -
-
- -validator_address: address -
-
- -
-
- -reference_gas_survey_quote: u64 -
-
- -
-
- -stake: u64 -
-
- -
-
- -commission_rate: u64 -
-
- -
-
- -pool_staking_reward: u64 -
-
- -
-
- -pool_token_exchange_rate: staking_pool::PoolTokenExchangeRate -
-
- -
-
- -tallying_rule_reporters: vector<address> -
-
- -
-
- -tallying_rule_global_score: u64 -
-
- -
-
- - -
- - - -## Struct `ValidatorEpochInfoEventV2` - -V2 of ValidatorEpochInfoEvent containing more information about the validator. - - -

-struct ValidatorEpochInfoEventV2 has copy, drop
-
- - - -
-Fields - - -
-
- -epoch: u64 -
-
- -
-
- -validator_address: address -
-
- -
-
- -reference_gas_survey_quote: u64 -
-
- -
-
- -stake: u64 -
-
- -
-
- -voting_power: u64 -
-
- -
-
- -commission_rate: u64 -
-
- -
-
- -pool_staking_reward: u64 -
-
- -
-
- -pool_token_exchange_rate: staking_pool::PoolTokenExchangeRate -
-
- -
-
- -tallying_rule_reporters: vector<address> -
-
- -
-
- -tallying_rule_global_score: u64 -
-
- -
-
- - -
- - - -## Struct `ValidatorJoinEvent` - -Event emitted every time a new validator joins the committee. -The epoch value corresponds to the first epoch this change takes place. - - -

-struct ValidatorJoinEvent has copy, drop
-
- - - -
-Fields - - -
-
- -epoch: u64 -
-
- -
-
- -validator_address: address -
-
- -
-
- -staking_pool_id: object::ID -
-
- -
-
- - -
- - - -## Struct `ValidatorLeaveEvent` - -Event emitted every time a validator leaves the committee. -The epoch value corresponds to the first epoch this change takes place. - - -

-struct ValidatorLeaveEvent has copy, drop
-
- - - -
-Fields - - -
-
- -epoch: u64 -
-
- -
-
- -validator_address: address -
-
- -
-
- -staking_pool_id: object::ID -
-
- -
-
- -is_voluntary: bool -
-
- -
-
- - -
- - - -## Constants - - - - - - -

-const MIN_STAKING_THRESHOLD: u64 = 1000000000;
-
- - - - - - - -

-const EInvalidCap: u64 = 101;
-
- - - - - - - -

-const ENotValidatorCandidate: u64 = 8;
-
- - - - - - - -

-const ACTIVE_OR_PENDING_VALIDATOR: u8 = 2;
-
- - - - - - - -

-const ACTIVE_VALIDATOR_ONLY: u8 = 1;
-
- - - - - - - -

-const ANY_VALIDATOR: u8 = 3;
-
- - - - - - - -

-const BASIS_POINT_DENOMINATOR: u128 = 10000;
-
- - - - - - - -

-const EAlreadyValidatorCandidate: u64 = 6;
-
- - - - - - - -

-const EDuplicateValidator: u64 = 2;
-
- - - - - - - -

-const EInvalidStakeAdjustmentAmount: u64 = 1;
-
- - - - - - - -

-const EMinJoiningStakeNotReached: u64 = 5;
-
- - - - - - - -

-const ENoPoolFound: u64 = 3;
-
- - - - - - - -

-const ENonValidatorInReportRecords: u64 = 0;
-
- - - - - - - -

-const ENotAPendingValidator: u64 = 12;
-
- - - - - - - -

-const ENotAValidator: u64 = 4;
-
- - - - - - - -

-const ENotActiveOrPendingValidator: u64 = 9;
-
- - - - - - - -

-const EStakingBelowThreshold: u64 = 10;
-
- - - - - - - -

-const EValidatorAlreadyRemoved: u64 = 11;
-
- - - - - - - -

-const EValidatorNotCandidate: u64 = 7;
-
- - - - - - - -

-const EValidatorSetEmpty: u64 = 13;
-
- - - - - -## Function `new` - - - -

-public(friend) fun new(init_active_validators: vector<validator::Validator>, ctx: &mut tx_context::TxContext): validator_set::ValidatorSet
-
- - - -
-Implementation - - -

-public(package) fun new(init_active_validators: vector<Validator>, ctx: &mut TxContext): ValidatorSet \{
-    let total_stake = calculate_total_stakes(&init_active_validators);
-    let mut staking_pool_mappings = table::new(ctx);
-    let num_validators = init_active_validators.length();
-    let mut i = 0;
-    while (i < num_validators) \{
-        let validator = &init_active_validators[i];
-        staking_pool_mappings.add(staking_pool_id(validator), iota_address(validator));
-        i = i + 1;
-    };
-    let mut validators = ValidatorSet \{
-        total_stake,
-        active_validators: init_active_validators,
-        pending_active_validators: table_vec::empty(ctx),
-        pending_removals: vector[],
-        staking_pool_mappings,
-        inactive_validators: table::new(ctx),
-        validator_candidates: table::new(ctx),
-        at_risk_validators: vec_map::empty(),
-        extra_fields: bag::new(ctx),
-    };
-    voting_power::set_voting_power(&mut validators.active_validators);
-    validators
-}
-
- - - -
- - - -## Function `request_add_validator_candidate` - -Called by -iota_system to add a new validator candidate. - - -

-public(friend) fun request_add_validator_candidate(self: &mut validator_set::ValidatorSet, validator: validator::Validator, ctx: &mut tx_context::TxContext)
-
- - - -
-Implementation - - -

-public(package) fun request_add_validator_candidate(
-    self: &mut ValidatorSet,
-    validator: Validator,
-    ctx: &mut TxContext,
-) \{
-    // The next assertions are not critical for the protocol, but they are here to catch problematic configs earlier.
-    assert!(
-        !is_duplicate_with_active_validator(self, &validator)
-            && !is_duplicate_with_pending_validator(self, &validator),
-        EDuplicateValidator
-    );
-    let validator_address = iota_address(&validator);
-    assert!(
-        !self.validator_candidates.contains(validator_address),
-        EAlreadyValidatorCandidate
-    );
-
-    assert!(validator.is_preactive(), EValidatorNotCandidate);
-    // Add validator to the candidates mapping and the pool id mappings so that users can start
-    // staking with this candidate.
-    self.staking_pool_mappings.add(staking_pool_id(&validator), validator_address);
-    self.validator_candidates.add(
-        iota_address(&validator),
-        validator_wrapper::create_v1(validator, ctx),
-    );
-}
-
- - - -
- - - -## Function `request_remove_validator_candidate` - -Called by -iota_system to remove a validator candidate, and move them to -inactive_validators. - - -

-public(friend) fun request_remove_validator_candidate(self: &mut validator_set::ValidatorSet, ctx: &mut tx_context::TxContext)
-
- - - -
-Implementation - - -

-public(package) fun request_remove_validator_candidate(self: &mut ValidatorSet, ctx: &mut TxContext) \{
-    let validator_address = ctx.sender();
-     assert!(
-        self.validator_candidates.contains(validator_address),
-        ENotValidatorCandidate
-    );
-    let wrapper = self.validator_candidates.remove(validator_address);
-    let mut validator = wrapper.destroy();
-    assert!(validator.is_preactive(), EValidatorNotCandidate);
-
-    let staking_pool_id = staking_pool_id(&validator);
-
-    // Remove the validator's staking pool from mappings.
-    self.staking_pool_mappings.remove(staking_pool_id);
-
-    // Deactivate the staking pool.
-    validator.deactivate(ctx.epoch());
-
-    // Add to the inactive tables.
-    self.inactive_validators.add(
-        staking_pool_id,
-        validator_wrapper::create_v1(validator, ctx),
-    );
-}
-
- - - -
- - - -## Function `request_add_validator` - -Called by -iota_system to add a new validator to -pending_active_validators, which will be -processed at the end of epoch. - - -

-public(friend) fun request_add_validator(self: &mut validator_set::ValidatorSet, min_joining_stake_amount: u64, ctx: &tx_context::TxContext)
-
- - - -
-Implementation - - -

-public(package) fun request_add_validator(self: &mut ValidatorSet, min_joining_stake_amount: u64, ctx: &TxContext) \{
-    let validator_address = ctx.sender();
-    assert!(
-        self.validator_candidates.contains(validator_address),
-        ENotValidatorCandidate
-    );
-    let wrapper = self.validator_candidates.remove(validator_address);
-    let validator = wrapper.destroy();
-    assert!(
-        !is_duplicate_with_active_validator(self, &validator)
-            && !is_duplicate_with_pending_validator(self, &validator),
-        EDuplicateValidator
-    );
-    assert!(validator.is_preactive(), EValidatorNotCandidate);
-    assert!(validator.total_stake_amount() >= min_joining_stake_amount, EMinJoiningStakeNotReached);
-
-    self.pending_active_validators.push_back(validator);
-}
-
- - - -
- - - -## Function `assert_no_pending_or_active_duplicates` - - - -

-public(friend) fun assert_no_pending_or_active_duplicates(self: &validator_set::ValidatorSet, validator: &validator::Validator)
-
- - - -
-Implementation - - -

-public(package) fun assert_no_pending_or_active_duplicates(self: &ValidatorSet, validator: &Validator) \{
-    // Validator here must be active or pending, and thus must be identified as duplicate exactly once.
-    assert!(
-        count_duplicates_vec(&self.active_validators, validator) +
-            count_duplicates_tablevec(&self.pending_active_validators, validator) == 1,
-        EDuplicateValidator
-    );
-}
-
- - - -
- - - -## Function `request_remove_validator` - -Called by -iota_system, to remove a validator. -The index of the validator is added to -pending_removals and -will be processed at the end of epoch. -Only an active validator can request to be removed. - - -

-public(friend) fun request_remove_validator(self: &mut validator_set::ValidatorSet, ctx: &tx_context::TxContext)
-
- - - -
-Implementation - - -

-public(package) fun request_remove_validator(
-    self: &mut ValidatorSet,
-    ctx: &TxContext,
-) \{
-    let validator_address = ctx.sender();
-    let mut validator_index_opt = find_validator(&self.active_validators, validator_address);
-    assert!(validator_index_opt.is_some(), ENotAValidator);
-    let validator_index = validator_index_opt.extract();
-    assert!(
-        !self.pending_removals.contains(&validator_index),
-        EValidatorAlreadyRemoved
-    );
-    self.pending_removals.push_back(validator_index);
-}
-
- - - -
- - - -## Function `request_add_stake` - -Called by -iota_system, to add a new stake to the validator. -This request is added to the validator's staking pool's pending stake entries, processed at the end -of the epoch. -Aborts in case the staking amount is smaller than MIN_STAKING_THRESHOLD - - -

-public(friend) fun request_add_stake(self: &mut validator_set::ValidatorSet, validator_address: address, stake: balance::Balance<iota::IOTA>, ctx: &mut tx_context::TxContext): staking_pool::StakedIota
-
- - - -
-Implementation - - -

-public(package) fun request_add_stake(
-    self: &mut ValidatorSet,
-    validator_address: address,
-    stake: Balance<IOTA>,
-    ctx: &mut TxContext,
-) : StakedIota \{
-    let iota_amount = stake.value();
-    assert!(iota_amount >= MIN_STAKING_THRESHOLD, EStakingBelowThreshold);
-    let validator = get_candidate_or_active_validator_mut(self, validator_address);
-    validator.request_add_stake(stake, ctx.sender(), ctx)
-}
-
- - - -
- - - -## Function `request_withdraw_stake` - -Called by -iota_system, to withdraw some share of a stake from the validator. The share to withdraw -is denoted by -principal_withdraw_amount. One of two things occurs in this function: -1. If the -staked_iota is staked with an active validator, the request is added to the validator's -staking pool's pending stake withdraw entries, processed at the end of the epoch. -2. If the -staked_iota was staked with a validator that is no longer active, -the stake and any rewards corresponding to it will be immediately processed. - - -

-public(friend) fun request_withdraw_stake(self: &mut validator_set::ValidatorSet, staked_iota: staking_pool::StakedIota, ctx: &tx_context::TxContext): balance::Balance<iota::IOTA>
-
- - - -
-Implementation - - -

-public(package) fun request_withdraw_stake(
-    self: &mut ValidatorSet,
-    staked_iota: StakedIota,
-    ctx: &TxContext,
-) : Balance<IOTA> \{
-    let staking_pool_id = pool_id(&staked_iota);
-    let validator =
-        if (self.staking_pool_mappings.contains(staking_pool_id)) \{ // This is an active validator.
-            let validator_address = self.staking_pool_mappings[pool_id(&staked_iota)];
-            get_candidate_or_active_validator_mut(self, validator_address)
-        } else \{ // This is an inactive pool.
-            assert!(self.inactive_validators.contains(staking_pool_id), ENoPoolFound);
-            let wrapper = &mut self.inactive_validators[staking_pool_id];
-            wrapper.load_validator_maybe_upgrade()
-        };
-    validator.request_withdraw_stake(staked_iota, ctx)
-}
-
- - - -
- - - -## Function `request_set_commission_rate` - - - -

-public(friend) fun request_set_commission_rate(self: &mut validator_set::ValidatorSet, new_commission_rate: u64, ctx: &tx_context::TxContext)
-
- - - -
-Implementation - - -

-public(package) fun request_set_commission_rate(
-    self: &mut ValidatorSet,
-    new_commission_rate: u64,
-    ctx: &TxContext,
-) \{
-    let validator_address = ctx.sender();
-    let validator = get_validator_mut(&mut self.active_validators, validator_address);
-    validator.request_set_commission_rate(new_commission_rate);
-}
-
- - - -
- - - -## Function `advance_epoch` - -Update the validator set at the end of epoch. -It does the following things: -1. Distribute stake award. -2. Process pending stake deposits and withdraws for each validator ( -adjust_stake). -3. Process pending stake deposits, and withdraws. -4. Process pending validator application and withdraws. -5. At the end, we calculate the total stake for the new epoch. - - -

-public(friend) fun advance_epoch(self: &mut validator_set::ValidatorSet, total_validator_rewards: &mut balance::Balance<iota::IOTA>, validator_report_records: &mut vec_map::VecMap<address, vec_set::VecSet<address>>, reward_slashing_rate: u64, low_stake_threshold: u64, very_low_stake_threshold: u64, low_stake_grace_period: u64, ctx: &mut tx_context::TxContext)
-
- - - -
-Implementation - - -

-public(package) fun advance_epoch(
-    self: &mut ValidatorSet,
-    total_validator_rewards: &mut Balance<IOTA>,
-    validator_report_records: &mut VecMap<address, VecSet<address>>,
-    reward_slashing_rate: u64,
-    low_stake_threshold: u64,
-    very_low_stake_threshold: u64,
-    low_stake_grace_period: u64,
-    ctx: &mut TxContext,
-) \{
-    let new_epoch = ctx.epoch() + 1;
-    let total_voting_power = voting_power::total_voting_power();
-
-    // Compute the reward distribution without taking into account the tallying rule slashing.
-    let unadjusted_staking_reward_amounts = compute_unadjusted_reward_distribution(
-        &self.active_validators,
-        total_voting_power,
-        total_validator_rewards.value(),
-    );
-
-    // Use the tallying rule report records for the epoch to compute validators that will be
-    // punished.
-    let slashed_validators = compute_slashed_validators(self, *validator_report_records);
-
-    let total_slashed_validator_voting_power = sum_voting_power_by_addresses(&self.active_validators, &slashed_validators);
-
-    // Compute the reward adjustments of slashed validators, to be taken into
-    // account in adjusted reward computation.
-    let (total_staking_reward_adjustment, individual_staking_reward_adjustments) =
-        compute_reward_adjustments(
-            get_validator_indices(&self.active_validators, &slashed_validators),
-            reward_slashing_rate,
-            &unadjusted_staking_reward_amounts,
-        );
-
-    // Compute the adjusted amounts of stake each validator should get given the tallying rule
-    // reward adjustments we computed before.
-    // `compute_adjusted_reward_distribution` must be called before `distribute_reward` and `adjust_stake_and_gas_price` to
-    // make sure we are using the current epoch's stake information to compute reward distribution.
-    let adjusted_staking_reward_amounts = compute_adjusted_reward_distribution(
-        &self.active_validators,
-        total_voting_power,
-        total_slashed_validator_voting_power,
-        unadjusted_staking_reward_amounts,
-        total_staking_reward_adjustment,
-        individual_staking_reward_adjustments,
-    );
-
-    // Distribute the rewards before adjusting stake so that we immediately start compounding
-    // the rewards for validators and stakers.
-    distribute_reward(
-        &mut self.active_validators,
-        &adjusted_staking_reward_amounts,
-        total_validator_rewards,
-        ctx
-    );
-
-    adjust_stake_and_gas_price(&mut self.active_validators);
-
-    process_pending_stakes_and_withdraws(&mut self.active_validators, ctx);
-
-    // Emit events after we have processed all the rewards distribution and pending stakes.
-    emit_validator_epoch_events(new_epoch, &self.active_validators, &adjusted_staking_reward_amounts,
-        validator_report_records, &slashed_validators);
-
-    // Note that all their staged next epoch metadata will be effectuated below.
-    process_pending_validators(self, new_epoch);
-
-    process_pending_removals(self, validator_report_records, ctx);
-
-    // kick low stake validators out.
-    update_and_process_low_stake_departures(
-        self,
-        low_stake_threshold,
-        very_low_stake_threshold,
-        low_stake_grace_period,
-        validator_report_records,
-        ctx
-    );
-
-    self.total_stake = calculate_total_stakes(&self.active_validators);
-
-    voting_power::set_voting_power(&mut self.active_validators);
-
-    // At this point, self.active_validators are updated for next epoch.
-    // Now we process the staged validator metadata.
-    effectuate_staged_metadata(self);
-}
-
- - - -
- - - -## Function `update_and_process_low_stake_departures` - - - -

-fun update_and_process_low_stake_departures(self: &mut validator_set::ValidatorSet, low_stake_threshold: u64, very_low_stake_threshold: u64, low_stake_grace_period: u64, validator_report_records: &mut vec_map::VecMap<address, vec_set::VecSet<address>>, ctx: &mut tx_context::TxContext)
-
- - - -
-Implementation - - -

-fun update_and_process_low_stake_departures(
-    self: &mut ValidatorSet,
-    low_stake_threshold: u64,
-    very_low_stake_threshold: u64,
-    low_stake_grace_period: u64,
-    validator_report_records: &mut VecMap<address, VecSet<address>>,
-    ctx: &mut TxContext
-) \{
-    // Iterate through all the active validators, record their low stake status, and kick them out if the condition is met.
-    let mut i = self.active_validators.length();
-    while (i > 0) \{
-        i = i - 1;
-        let validator_ref = &self.active_validators[i];
-        let validator_address = validator_ref.iota_address();
-        let stake = validator_ref.total_stake_amount();
-        if (stake >= low_stake_threshold) \{
-            // The validator is safe. We remove their entry from the at_risk map if there exists one.
-            if (self.at_risk_validators.contains(&validator_address)) \{
-               self.at_risk_validators.remove(&validator_address);
-            }
-        } else if (stake >= very_low_stake_threshold) \{
-            // The stake is a bit below the threshold so we increment the entry of the validator in the map.
-            let new_low_stake_period =
-                if (self.at_risk_validators.contains(&validator_address)) \{
-                    let num_epochs = &mut self.at_risk_validators[&validator_address];
-                    *num_epochs = *num_epochs + 1;
-                    *num_epochs
-                } else \{
-                    self.at_risk_validators.insert(validator_address, 1);
-                    1
-                };
-
-            // If the grace period has passed, the validator has to leave us.
-            if (new_low_stake_period > low_stake_grace_period) \{
-                let validator = self.active_validators.remove(i);
-                process_validator_departure(self, validator, validator_report_records, false /* the validator is kicked out involuntarily */, ctx);
-            }
-        } else \{
-            // The validator's stake is lower than the very low threshold so we kick them out immediately.
-            let validator = self.active_validators.remove(i);
-            process_validator_departure(self, validator, validator_report_records, false /* the validator is kicked out involuntarily */, ctx);
-        }
-    }
-}
-
- - - -
- - - -## Function `effectuate_staged_metadata` - -Effectutate pending next epoch metadata if they are staged. - - -

-fun effectuate_staged_metadata(self: &mut validator_set::ValidatorSet)
-
- - - -
-Implementation - - -

-fun effectuate_staged_metadata(
-    self: &mut ValidatorSet,
-) \{
-    let num_validators = self.active_validators.length();
-    let mut i = 0;
-    while (i < num_validators) \{
-        let validator = &mut self.active_validators[i];
-        validator.effectuate_staged_metadata();
-        i = i + 1;
-    }
-}
-
- - - -
- - - -## Function `derive_reference_gas_price` - -Called by -iota_system to derive reference gas price for the new epoch. -Derive the reference gas price based on the gas price quote submitted by each validator. -The returned gas price should be greater than or equal to 2/3 of the validators submitted -gas price, weighted by stake. - - -

-public fun derive_reference_gas_price(self: &validator_set::ValidatorSet): u64
-
- - - -
-Implementation - - -

-public fun derive_reference_gas_price(self: &ValidatorSet): u64 \{
-    let vs = &self.active_validators;
-    let num_validators = vs.length();
-    let mut entries = vector[];
-    let mut i = 0;
-    while (i < num_validators) \{
-        let v = &vs[i];
-        entries.push_back(
-            pq::new_entry(v.gas_price(), v.voting_power())
-        );
-        i = i + 1;
-    };
-    // Build a priority queue that will pop entries with gas price from the highest to the lowest.
-    let mut pq = pq::new(entries);
-    let mut sum = 0;
-    let threshold = voting_power::total_voting_power() - voting_power::quorum_threshold();
-    let mut result = 0;
-    while (sum < threshold) \{
-        let (gas_price, voting_power) = pq.pop_max();
-        result = gas_price;
-        sum = sum + voting_power;
-    };
-    result
-}
-
- - - -
- - - -## Function `total_stake` - - - -

-public fun total_stake(self: &validator_set::ValidatorSet): u64
-
- - - -
-Implementation - - -

-public fun total_stake(self: &ValidatorSet): u64 \{
-    self.total_stake
-}
-
- - - -
- - - -## Function `validator_total_stake_amount` - - - -

-public fun validator_total_stake_amount(self: &validator_set::ValidatorSet, validator_address: address): u64
-
- - - -
-Implementation - - -

-public fun validator_total_stake_amount(self: &ValidatorSet, validator_address: address): u64 \{
-    let validator = get_validator_ref(&self.active_validators, validator_address);
-    validator.total_stake_amount()
-}
-
- - - -
- - - -## Function `validator_stake_amount` - - - -

-public fun validator_stake_amount(self: &validator_set::ValidatorSet, validator_address: address): u64
-
- - - -
-Implementation - - -

-public fun validator_stake_amount(self: &ValidatorSet, validator_address: address): u64 \{
-    let validator = get_validator_ref(&self.active_validators, validator_address);
-    validator.stake_amount()
-}
-
- - - -
- - - -## Function `validator_staking_pool_id` - - - -

-public fun validator_staking_pool_id(self: &validator_set::ValidatorSet, validator_address: address): object::ID
-
- - - -
-Implementation - - -

-public fun validator_staking_pool_id(self: &ValidatorSet, validator_address: address): ID \{
-    let validator = get_validator_ref(&self.active_validators, validator_address);
-    validator.staking_pool_id()
-}
-
- - - -
- - - -## Function `staking_pool_mappings` - - - -

-public fun staking_pool_mappings(self: &validator_set::ValidatorSet): &table::Table<object::ID, address>
-
- - - -
-Implementation - - -

-public fun staking_pool_mappings(self: &ValidatorSet): &Table<ID, address> \{
-    &self.staking_pool_mappings
-}
-
- - - -
- - - -## Function `pool_exchange_rates` - - - -

-public(friend) fun pool_exchange_rates(self: &mut validator_set::ValidatorSet, pool_id: &object::ID): &table::Table<u64, staking_pool::PoolTokenExchangeRate>
-
- - - -
-Implementation - - -

-public(package) fun pool_exchange_rates(
-    self: &mut ValidatorSet, pool_id: &ID
-) : &Table<u64, PoolTokenExchangeRate> \{
-    let validator =
-        // If the pool id is recorded in the mapping, then it must be either candidate or active.
-        if (self.staking_pool_mappings.contains(*pool_id)) \{
-            let validator_address = self.staking_pool_mappings[*pool_id];
-            get_active_or_pending_or_candidate_validator_ref(self, validator_address, ANY_VALIDATOR)
-        } else \{ // otherwise it's inactive
-            let wrapper = &mut self.inactive_validators[*pool_id];
-            wrapper.load_validator_maybe_upgrade()
-        };
-	validator.get_staking_pool_ref().exchange_rates()
-}
-
- - - -
- - - -## Function `next_epoch_validator_count` - -Get the total number of validators in the next epoch. - - -

-public(friend) fun next_epoch_validator_count(self: &validator_set::ValidatorSet): u64
-
- - - -
-Implementation - - -

-public(package) fun next_epoch_validator_count(self: &ValidatorSet): u64 \{
-    self.active_validators.length() - self.pending_removals.length() + self.pending_active_validators.length()
-}
-
- - - -
- - - -## Function `is_active_validator_by_iota_address` - -Returns true iff the address exists in active validators. - - -

-public(friend) fun is_active_validator_by_iota_address(self: &validator_set::ValidatorSet, validator_address: address): bool
-
- - - -
-Implementation - - -

-public(package) fun is_active_validator_by_iota_address(
-    self: &ValidatorSet,
-    validator_address: address,
-): bool \{
-   find_validator(&self.active_validators, validator_address).is_some()
-}
-
- - - -
- - - -## Function `is_duplicate_with_active_validator` - -Checks whether -new_validator is duplicate with any currently active validators. -It differs from -is_active_validator_by_iota_address in that the former checks -only the iota address but this function looks at more metadata. - - -

-fun is_duplicate_with_active_validator(self: &validator_set::ValidatorSet, new_validator: &validator::Validator): bool
-
- - - -
-Implementation - - -

-fun is_duplicate_with_active_validator(self: &ValidatorSet, new_validator: &Validator): bool \{
-    is_duplicate_validator(&self.active_validators, new_validator)
-}
-
- - - -
- - - -## Function `is_duplicate_validator` - - - -

-public(friend) fun is_duplicate_validator(validators: &vector<validator::Validator>, new_validator: &validator::Validator): bool
-
- - - -
-Implementation - - -

-public(package) fun is_duplicate_validator(validators: &vector<Validator>, new_validator: &Validator): bool \{
-    count_duplicates_vec(validators, new_validator) > 0
-}
-
- - - -
- - - -## Function `count_duplicates_vec` - - - -

-fun count_duplicates_vec(validators: &vector<validator::Validator>, validator: &validator::Validator): u64
-
- - - -
-Implementation - - -

-fun count_duplicates_vec(validators: &vector<Validator>, validator: &Validator): u64 \{
-    let len = validators.length();
-    let mut i = 0;
-    let mut result = 0;
-    while (i < len) \{
-        let v = &validators[i];
-        if (v.is_duplicate(validator)) \{
-            result = result + 1;
-        };
-        i = i + 1;
-    };
-    result
-}
-
- - - -
- - - -## Function `is_duplicate_with_pending_validator` - -Checks whether -new_validator is duplicate with any currently pending validators. - - -

-fun is_duplicate_with_pending_validator(self: &validator_set::ValidatorSet, new_validator: &validator::Validator): bool
-
- - - -
-Implementation - - -

-fun is_duplicate_with_pending_validator(self: &ValidatorSet, new_validator: &Validator): bool \{
-    count_duplicates_tablevec(&self.pending_active_validators, new_validator) > 0
-}
-
- - - -
- - - -## Function `count_duplicates_tablevec` - - - -

-fun count_duplicates_tablevec(validators: &table_vec::TableVec<validator::Validator>, validator: &validator::Validator): u64
-
- - - -
-Implementation - - -

-fun count_duplicates_tablevec(validators: &TableVec<Validator>, validator: &Validator): u64 \{
-    let len = validators.length();
-    let mut i = 0;
-    let mut result = 0;
-    while (i < len) \{
-        let v = &validators[i];
-        if (v.is_duplicate(validator)) \{
-            result = result + 1;
-        };
-        i = i + 1;
-    };
-    result
-}
-
- - - -
- - - -## Function `get_candidate_or_active_validator_mut` - -Get mutable reference to either a candidate or an active validator by address. - - -

-fun get_candidate_or_active_validator_mut(self: &mut validator_set::ValidatorSet, validator_address: address): &mut validator::Validator
-
- - - -
-Implementation - - -

-fun get_candidate_or_active_validator_mut(self: &mut ValidatorSet, validator_address: address): &mut Validator \{
-    if (self.validator_candidates.contains(validator_address)) \{
-        let wrapper = &mut self.validator_candidates[validator_address];
-        return wrapper.load_validator_maybe_upgrade()
-    };
-    get_validator_mut(&mut self.active_validators, validator_address)
-}
-
- - - -
- - - -## Function `find_validator` - -Find validator by -validator_address, in -validators. -Returns (true, index) if the validator is found, and the index is its index in the list. -If not found, returns (false, 0). - - -

-fun find_validator(validators: &vector<validator::Validator>, validator_address: address): option::Option<u64>
-
- - - -
-Implementation - - -

-fun find_validator(validators: &vector<Validator>, validator_address: address): Option<u64> \{
-    let length = validators.length();
-    let mut i = 0;
-    while (i < length) \{
-        let v = &validators[i];
-        if (v.iota_address() == validator_address) \{
-            return option::some(i)
-        };
-        i = i + 1;
-    };
-    option::none()
-}
-
- - - -
- - - -## Function `find_validator_from_table_vec` - -Find validator by -validator_address, in -validators. -Returns (true, index) if the validator is found, and the index is its index in the list. -If not found, returns (false, 0). - - -

-fun find_validator_from_table_vec(validators: &table_vec::TableVec<validator::Validator>, validator_address: address): option::Option<u64>
-
- - - -
-Implementation - - -

-fun find_validator_from_table_vec(validators: &TableVec<Validator>, validator_address: address): Option<u64> \{
-    let length = validators.length();
-    let mut i = 0;
-    while (i < length) \{
-        let v = &validators[i];
-        if (v.iota_address() == validator_address) \{
-            return option::some(i)
-        };
-        i = i + 1;
-    };
-    option::none()
-}
-
- - - -
- - - -## Function `get_validator_indices` - -Given a vector of validator addresses, return their indices in the validator set. -Aborts if any address isn't in the given validator set. - - -

-fun get_validator_indices(validators: &vector<validator::Validator>, validator_addresses: &vector<address>): vector<u64>
-
- - - -
-Implementation - - -

-fun get_validator_indices(validators: &vector<Validator>, validator_addresses: &vector<address>): vector<u64> \{
-    let length = validator_addresses.length();
-    let mut i = 0;
-    let mut res = vector[];
-    while (i < length) \{
-        let addr = validator_addresses[i];
-        let index_opt = find_validator(validators, addr);
-        assert!(index_opt.is_some(), ENotAValidator);
-        res.push_back(index_opt.destroy_some());
-        i = i + 1;
-    };
-    res
-}
-
- - - -
- - - -## Function `get_validator_mut` - - - -

-public(friend) fun get_validator_mut(validators: &mut vector<validator::Validator>, validator_address: address): &mut validator::Validator
-
- - - -
-Implementation - - -

-public(package) fun get_validator_mut(
-    validators: &mut vector<Validator>,
-    validator_address: address,
-): &mut Validator \{
-    let mut validator_index_opt = find_validator(validators, validator_address);
-    assert!(validator_index_opt.is_some(), ENotAValidator);
-    let validator_index = validator_index_opt.extract();
-    &mut validators[validator_index]
-}
-
- - - -
- - - -## Function `get_active_or_pending_or_candidate_validator_mut` - -Get mutable reference to an active or (if active does not exist) pending or (if pending and -active do not exist) or candidate validator by address. -Note: this function should be called carefully, only after verifying the transaction -sender has the ability to modify the -Validator. - - -

-fun get_active_or_pending_or_candidate_validator_mut(self: &mut validator_set::ValidatorSet, validator_address: address, include_candidate: bool): &mut validator::Validator
-
- - - -
-Implementation - - -

-fun get_active_or_pending_or_candidate_validator_mut(
-    self: &mut ValidatorSet,
-    validator_address: address,
-    include_candidate: bool,
-): &mut Validator \{
-    let mut validator_index_opt = find_validator(&self.active_validators, validator_address);
-    if (validator_index_opt.is_some()) \{
-        let validator_index = validator_index_opt.extract();
-        return &mut self.active_validators[validator_index]
-    };
-    let mut validator_index_opt = find_validator_from_table_vec(&self.pending_active_validators, validator_address);
-    // consider both pending validators and the candidate ones
-    if (validator_index_opt.is_some()) \{
-        let validator_index = validator_index_opt.extract();
-        return &mut self.pending_active_validators[validator_index]
-    };
-    assert!(include_candidate, ENotActiveOrPendingValidator);
-    let wrapper = &mut self.validator_candidates[validator_address];
-    wrapper.load_validator_maybe_upgrade()
-}
-
- - - -
- - - -## Function `get_validator_mut_with_verified_cap` - - - -

-public(friend) fun get_validator_mut_with_verified_cap(self: &mut validator_set::ValidatorSet, verified_cap: &validator_cap::ValidatorOperationCap, include_candidate: bool): &mut validator::Validator
-
- - - -
-Implementation - - -

-public(package) fun get_validator_mut_with_verified_cap(
-    self: &mut ValidatorSet,
-    verified_cap: &ValidatorOperationCap,
-    include_candidate: bool,
-): &mut Validator \{
-    get_active_or_pending_or_candidate_validator_mut(self, *verified_cap.verified_operation_cap_address(), include_candidate)
-}
-
- - - -
- - - -## Function `get_validator_mut_with_ctx` - - - -

-public(friend) fun get_validator_mut_with_ctx(self: &mut validator_set::ValidatorSet, ctx: &tx_context::TxContext): &mut validator::Validator
-
- - - -
-Implementation - - -

-public(package) fun get_validator_mut_with_ctx(
-    self: &mut ValidatorSet,
-    ctx: &TxContext,
-): &mut Validator \{
-    let validator_address = ctx.sender();
-    get_active_or_pending_or_candidate_validator_mut(self, validator_address, false)
-}
-
- - - -
- - - -## Function `get_validator_mut_with_ctx_including_candidates` - - - -

-public(friend) fun get_validator_mut_with_ctx_including_candidates(self: &mut validator_set::ValidatorSet, ctx: &tx_context::TxContext): &mut validator::Validator
-
- - - -
-Implementation - - -

-public(package) fun get_validator_mut_with_ctx_including_candidates(
-    self: &mut ValidatorSet,
-    ctx: &TxContext,
-): &mut Validator \{
-    let validator_address = ctx.sender();
-    get_active_or_pending_or_candidate_validator_mut(self, validator_address, true)
-}
-
- - - -
- - - -## Function `get_validator_ref` - - - -

-fun get_validator_ref(validators: &vector<validator::Validator>, validator_address: address): &validator::Validator
-
- - - -
-Implementation - - -

-fun get_validator_ref(
-    validators: &vector<Validator>,
-    validator_address: address,
-): &Validator \{
-    let mut validator_index_opt = find_validator(validators, validator_address);
-    assert!(validator_index_opt.is_some(), ENotAValidator);
-    let validator_index = validator_index_opt.extract();
-    &validators[validator_index]
-}
-
- - - -
- - - -## Function `get_active_or_pending_or_candidate_validator_ref` - - - -

-public(friend) fun get_active_or_pending_or_candidate_validator_ref(self: &mut validator_set::ValidatorSet, validator_address: address, which_validator: u8): &validator::Validator
-
- - - -
-Implementation - - -

-public(package) fun get_active_or_pending_or_candidate_validator_ref(
-    self: &mut ValidatorSet,
-    validator_address: address,
-    which_validator: u8,
-): &Validator \{
-    let mut validator_index_opt = find_validator(&self.active_validators, validator_address);
-    if (validator_index_opt.is_some() || which_validator == ACTIVE_VALIDATOR_ONLY) \{
-        let validator_index = validator_index_opt.extract();
-        return &self.active_validators[validator_index]
-    };
-    let mut validator_index_opt = find_validator_from_table_vec(&self.pending_active_validators, validator_address);
-    if (validator_index_opt.is_some() || which_validator == ACTIVE_OR_PENDING_VALIDATOR) \{
-        let validator_index = validator_index_opt.extract();
-        return &self.pending_active_validators[validator_index]
-    };
-    self.validator_candidates[validator_address].load_validator_maybe_upgrade()
-}
-
- - - -
- - - -## Function `get_active_validator_ref` - - - -

-public fun get_active_validator_ref(self: &validator_set::ValidatorSet, validator_address: address): &validator::Validator
-
- - - -
-Implementation - - -

-public fun get_active_validator_ref(
-    self: &ValidatorSet,
-    validator_address: address,
-): &Validator \{
-    let mut validator_index_opt = find_validator(&self.active_validators, validator_address);
-    assert!(validator_index_opt.is_some(), ENotAValidator);
-    let validator_index = validator_index_opt.extract();
-    &self.active_validators[validator_index]
-}
-
- - - -
- - - -## Function `get_pending_validator_ref` - - - -

-public fun get_pending_validator_ref(self: &validator_set::ValidatorSet, validator_address: address): &validator::Validator
-
- - - -
-Implementation - - -

-public fun get_pending_validator_ref(
-    self: &ValidatorSet,
-    validator_address: address,
-): &Validator \{
-    let mut validator_index_opt = find_validator_from_table_vec(&self.pending_active_validators, validator_address);
-    assert!(validator_index_opt.is_some(), ENotAPendingValidator);
-    let validator_index = validator_index_opt.extract();
-    &self.pending_active_validators[validator_index]
-}
-
- - - -
- - - -## Function `verify_cap` - -Verify the capability is valid for a Validator. -If -active_validator_only is true, only verify the Cap for an active validator. -Otherwise, verify the Cap for au either active or pending validator. - - -

-public(friend) fun verify_cap(self: &mut validator_set::ValidatorSet, cap: &validator_cap::UnverifiedValidatorOperationCap, which_validator: u8): validator_cap::ValidatorOperationCap
-
- - - -
-Implementation - - -

-public(package) fun verify_cap(
-    self: &mut ValidatorSet,
-    cap: &UnverifiedValidatorOperationCap,
-    which_validator: u8,
-): ValidatorOperationCap \{
-    let cap_address = *cap.unverified_operation_cap_address();
-    let validator =
-        if (which_validator == ACTIVE_VALIDATOR_ONLY)
-            get_active_validator_ref(self, cap_address)
-        else
-            get_active_or_pending_or_candidate_validator_ref(self, cap_address, which_validator);
-    assert!(validator.operation_cap_id() == &object::id(cap), EInvalidCap);
-    validator_cap::new_from_unverified(cap)
-}
-
- - - -
- - - -## Function `process_pending_removals` - -Process the pending withdraw requests. For each pending request, the validator -is removed from -validators and its staking pool is put into the -inactive_validators table. - - -

-fun process_pending_removals(self: &mut validator_set::ValidatorSet, validator_report_records: &mut vec_map::VecMap<address, vec_set::VecSet<address>>, ctx: &mut tx_context::TxContext)
-
- - - -
-Implementation - - -

-fun process_pending_removals(
-    self: &mut ValidatorSet,
-    validator_report_records: &mut VecMap<address, VecSet<address>>,
-    ctx: &mut TxContext,
-) \{
-    sort_removal_list(&mut self.pending_removals);
-    while (!self.pending_removals.is_empty()) \{
-        let index = self.pending_removals.pop_back();
-        let validator = self.active_validators.remove(index);
-        process_validator_departure(self, validator, validator_report_records, true /* the validator removes itself voluntarily */, ctx);
-    }
-}
-
- - - -
- - - -## Function `process_validator_departure` - - - -

-fun process_validator_departure(self: &mut validator_set::ValidatorSet, validator: validator::Validator, validator_report_records: &mut vec_map::VecMap<address, vec_set::VecSet<address>>, is_voluntary: bool, ctx: &mut tx_context::TxContext)
-
- - - -
-Implementation - - -

-fun process_validator_departure(
-    self: &mut ValidatorSet,
-    mut validator: Validator,
-    validator_report_records: &mut VecMap<address, VecSet<address>>,
-    is_voluntary: bool,
-    ctx: &mut TxContext,
-) \{
-    let new_epoch = ctx.epoch() + 1;
-    let validator_address = validator.iota_address();
-    let validator_pool_id = staking_pool_id(&validator);
-
-    // Remove the validator from our tables.
-    self.staking_pool_mappings.remove(validator_pool_id);
-    if (self.at_risk_validators.contains(&validator_address)) \{
-        self.at_risk_validators.remove(&validator_address);
-    };
-
-    self.total_stake = self.total_stake - validator.total_stake_amount();
-
-    clean_report_records_leaving_validator(validator_report_records, validator_address);
-
-    event::emit(
-        ValidatorLeaveEvent \{
-            epoch: new_epoch,
-            validator_address,
-            staking_pool_id: staking_pool_id(&validator),
-            is_voluntary,
-        }
-    );
-
-    // Deactivate the validator and its staking pool
-    validator.deactivate(new_epoch);
-    self.inactive_validators.add(
-        validator_pool_id,
-        validator_wrapper::create_v1(validator, ctx),
-    );
-}
-
- - - -
- - - -## Function `clean_report_records_leaving_validator` - - - -

-fun clean_report_records_leaving_validator(validator_report_records: &mut vec_map::VecMap<address, vec_set::VecSet<address>>, leaving_validator_addr: address)
-
- - - -
-Implementation - - -

-fun clean_report_records_leaving_validator(
-    validator_report_records: &mut VecMap<address, VecSet<address>>,
-    leaving_validator_addr: address
-) \{
-    // Remove the records about this validator
-    if (validator_report_records.contains(&leaving_validator_addr)) \{
-        validator_report_records.remove(&leaving_validator_addr);
-    };
-
-    // Remove the reports submitted by this validator
-    let reported_validators = validator_report_records.keys();
-    let length = reported_validators.length();
-    let mut i = 0;
-    while (i < length) \{
-        let reported_validator_addr = &reported_validators[i];
-        let reporters = &mut validator_report_records[reported_validator_addr];
-        if (reporters.contains(&leaving_validator_addr)) \{
-            reporters.remove(&leaving_validator_addr);
-            if (reporters.is_empty()) \{
-                validator_report_records.remove(reported_validator_addr);
-            };
-        };
-        i = i + 1;
-    }
-}
-
- - - -
- - - -## Function `process_pending_validators` - -Process the pending new validators. They are activated and inserted into -validators. - - -

-fun process_pending_validators(self: &mut validator_set::ValidatorSet, new_epoch: u64)
-
- - - -
-Implementation - - -

-fun process_pending_validators(
-    self: &mut ValidatorSet, new_epoch: u64,
-) \{
-    while (!self.pending_active_validators.is_empty()) \{
-        let mut validator = self.pending_active_validators.pop_back();
-        validator.activate(new_epoch);
-        event::emit(
-            ValidatorJoinEvent \{
-                epoch: new_epoch,
-                validator_address: validator.iota_address(),
-                staking_pool_id: staking_pool_id(&validator),
-            }
-        );
-        self.active_validators.push_back(validator);
-    }
-}
-
- - - -
- - - -## Function `sort_removal_list` - -Sort all the pending removal indexes. - - -

-fun sort_removal_list(withdraw_list: &mut vector<u64>)
-
- - - -
-Implementation - - -

-fun sort_removal_list(withdraw_list: &mut vector<u64>) \{
-    let length = withdraw_list.length();
-    let mut i = 1;
-    while (i < length) \{
-        let cur = withdraw_list[i];
-        let mut j = i;
-        while (j > 0) \{
-            j = j - 1;
-            if (withdraw_list[j] > cur) \{
-                withdraw_list.swap(j, j + 1);
-            } else \{
-                break
-            };
-        };
-        i = i + 1;
-    };
-}
-
- - - -
- - - -## Function `process_pending_stakes_and_withdraws` - -Process all active validators' pending stake deposits and withdraws. - - -

-fun process_pending_stakes_and_withdraws(validators: &mut vector<validator::Validator>, ctx: &tx_context::TxContext)
-
- - - -
-Implementation - - -

-fun process_pending_stakes_and_withdraws(
-    validators: &mut vector<Validator>, ctx: &TxContext
-) \{
-    let length = validators.length();
-    let mut i = 0;
-    while (i < length) \{
-        let validator = &mut validators[i];
-        validator.process_pending_stakes_and_withdraws(ctx);
-        i = i + 1;
-    }
-}
-
- - - -
- - - -## Function `calculate_total_stakes` - -Calculate the total active validator stake. - - -

-fun calculate_total_stakes(validators: &vector<validator::Validator>): u64
-
- - - -
-Implementation - - -

-fun calculate_total_stakes(validators: &vector<Validator>): u64 \{
-    let mut stake = 0;
-    let length = validators.length();
-    let mut i = 0;
-    while (i < length) \{
-        let v = &validators[i];
-        stake = stake + v.total_stake_amount();
-        i = i + 1;
-    };
-    stake
-}
-
- - - -
- - - -## Function `adjust_stake_and_gas_price` - -Process the pending stake changes for each validator. - - -

-fun adjust_stake_and_gas_price(validators: &mut vector<validator::Validator>)
-
- - - -
-Implementation - - -

-fun adjust_stake_and_gas_price(validators: &mut vector<Validator>) \{
-    let length = validators.length();
-    let mut i = 0;
-    while (i < length) \{
-        let validator = &mut validators[i];
-        validator.adjust_stake_and_gas_price();
-        i = i + 1;
-    }
-}
-
- - - -
- - - -## Function `compute_reward_adjustments` - -Compute both the individual reward adjustments and total reward adjustment for staking rewards. - - -

-fun compute_reward_adjustments(slashed_validator_indices: vector<u64>, reward_slashing_rate: u64, unadjusted_staking_reward_amounts: &vector<u64>): (u64, vec_map::VecMap<u64, u64>)
-
- - - -
-Implementation - - -

-fun compute_reward_adjustments(
-    mut slashed_validator_indices: vector<u64>,
-    reward_slashing_rate: u64,
-    unadjusted_staking_reward_amounts: &vector<u64>,
-): (
-    u64, // sum of staking reward adjustments
-    VecMap<u64, u64>, // mapping of individual validator's staking reward adjustment from index -> amount
-) \{
-    let mut total_staking_reward_adjustment = 0;
-    let mut individual_staking_reward_adjustments = vec_map::empty();
-
-    while (!slashed_validator_indices.is_empty()) \{
-        let validator_index = slashed_validator_indices.pop_back();
-
-        // Use the slashing rate to compute the amount of staking rewards slashed from this punished validator.
-        let unadjusted_staking_reward = unadjusted_staking_reward_amounts[validator_index];
-        let staking_reward_adjustment_u128 =
-            unadjusted_staking_reward as u128 * (reward_slashing_rate as u128)
-            / BASIS_POINT_DENOMINATOR;
-
-        // Insert into individual mapping and record into the total adjustment sum.
-        individual_staking_reward_adjustments.insert(validator_index, staking_reward_adjustment_u128 as u64);
-        total_staking_reward_adjustment = total_staking_reward_adjustment + (staking_reward_adjustment_u128 as u64);
-    };
-
-    (total_staking_reward_adjustment, individual_staking_reward_adjustments)
-}
-
- - - -
- - - -## Function `compute_slashed_validators` - -Process the validator report records of the epoch and return the addresses of the -non-performant validators according to the input threshold. - - -

-fun compute_slashed_validators(self: &validator_set::ValidatorSet, validator_report_records: vec_map::VecMap<address, vec_set::VecSet<address>>): vector<address>
-
- - - -
-Implementation - - -

-fun compute_slashed_validators(
-    self: &ValidatorSet,
-    mut validator_report_records: VecMap<address, VecSet<address>>,
-): vector<address> \{
-    let mut slashed_validators = vector[];
-    while (!validator_report_records.is_empty()) \{
-        let (validator_address, reporters) = validator_report_records.pop();
-        assert!(
-            is_active_validator_by_iota_address(self, validator_address),
-            ENonValidatorInReportRecords,
-        );
-        // Sum up the voting power of validators that have reported this validator and check if it has
-        // passed the slashing threshold.
-        let reporter_votes = sum_voting_power_by_addresses(&self.active_validators, &reporters.into_keys());
-        if (reporter_votes >= voting_power::quorum_threshold()) \{
-            slashed_validators.push_back(validator_address);
-        }
-    };
-    slashed_validators
-}
-
- - - -
- - - -## Function `compute_unadjusted_reward_distribution` - -Given the current list of active validators, the total stake and total reward, -calculate the amount of reward each validator should get, without taking into -account the tallying rule results. -Returns the unadjusted amounts of staking reward for each validator. - - -

-fun compute_unadjusted_reward_distribution(validators: &vector<validator::Validator>, total_voting_power: u64, total_staking_reward: u64): vector<u64>
-
- - - -
-Implementation - - -

-fun compute_unadjusted_reward_distribution(
-    validators: &vector<Validator>,
-    total_voting_power: u64,
-    total_staking_reward: u64,
-): vector<u64> \{
-    let mut staking_reward_amounts = vector[];
-    let length = validators.length();
-    let mut i = 0;
-    while (i < length) \{
-        let validator = &validators[i];
-        // Integer divisions will truncate the results. Because of this, we expect that at the end
-        // there will be some reward remaining in `total_staking_reward`.
-        // Use u128 to avoid multiplication overflow.
-        let voting_power: u128 = validator.voting_power() as u128;
-        let reward_amount = voting_power * (total_staking_reward as u128) / (total_voting_power as u128);
-        staking_reward_amounts.push_back(reward_amount as u64);
-        i = i + 1;
-    };
-    staking_reward_amounts
-}
-
- - - -
- - - -## Function `compute_adjusted_reward_distribution` - -Use the reward adjustment info to compute the adjusted rewards each validator should get. -Returns the staking rewards each validator gets. -The staking rewards are shared with the stakers. - - -

-fun compute_adjusted_reward_distribution(validators: &vector<validator::Validator>, total_voting_power: u64, total_slashed_validator_voting_power: u64, unadjusted_staking_reward_amounts: vector<u64>, total_staking_reward_adjustment: u64, individual_staking_reward_adjustments: vec_map::VecMap<u64, u64>): vector<u64>
-
- - - -
-Implementation - - -

-fun compute_adjusted_reward_distribution(
-    validators: &vector<Validator>,
-    total_voting_power: u64,
-    total_slashed_validator_voting_power: u64,
-    unadjusted_staking_reward_amounts: vector<u64>,
-    total_staking_reward_adjustment: u64,
-    individual_staking_reward_adjustments: VecMap<u64, u64>,
-): vector<u64> \{
-    let total_unslashed_validator_voting_power = total_voting_power - total_slashed_validator_voting_power;
-    let mut adjusted_staking_reward_amounts = vector[];
-
-    let length = validators.length();
-
-    let mut i = 0;
-    while (i < length) \{
-        let validator = &validators[i];
-        // Integer divisions will truncate the results. Because of this, we expect that at the end
-        // there will be some reward remaining in `total_reward`.
-        // Use u128 to avoid multiplication overflow.
-        let voting_power = validator.voting_power() as u128;
-
-        // Compute adjusted staking reward.
-        let unadjusted_staking_reward_amount = unadjusted_staking_reward_amounts[i];
-        let adjusted_staking_reward_amount =
-            // If the validator is one of the slashed ones, then subtract the adjustment.
-            if (individual_staking_reward_adjustments.contains(&i)) \{
-                let adjustment = individual_staking_reward_adjustments[&i];
-                unadjusted_staking_reward_amount - adjustment
-            } else \{
-                // Otherwise the slashed rewards should be distributed among the unslashed
-                // validators so add the corresponding adjustment.
-                let adjustment = total_staking_reward_adjustment as u128 * voting_power
-                               / (total_unslashed_validator_voting_power as u128);
-                unadjusted_staking_reward_amount + (adjustment as u64)
-            };
-        adjusted_staking_reward_amounts.push_back(adjusted_staking_reward_amount);
-
-        i = i + 1;
-    };
-
-    adjusted_staking_reward_amounts
-}
-
- - - -
- - - -## Function `distribute_reward` - - - -

-fun distribute_reward(validators: &mut vector<validator::Validator>, adjusted_staking_reward_amounts: &vector<u64>, staking_rewards: &mut balance::Balance<iota::IOTA>, ctx: &mut tx_context::TxContext)
-
- - - -
-Implementation - - -

-fun distribute_reward(
-    validators: &mut vector<Validator>,
-    adjusted_staking_reward_amounts: &vector<u64>,
-    staking_rewards: &mut Balance<IOTA>,
-    ctx: &mut TxContext
-) \{
-    let length = validators.length();
-    assert!(length > 0, EValidatorSetEmpty);
-    let mut i = 0;
-    while (i < length) \{
-        let validator = &mut validators[i];
-        let staking_reward_amount = adjusted_staking_reward_amounts[i];
-        let mut staker_reward = staking_rewards.split(staking_reward_amount);
-
-        // Validator takes a cut of the rewards as commission.
-        let validator_commission_amount = (staking_reward_amount as u128) * (validator.commission_rate() as u128) / BASIS_POINT_DENOMINATOR;
-
-        // The validator reward = commission.
-        let validator_reward = staker_reward.split(validator_commission_amount as u64);
-
-        // Add rewards to the validator. Don't try and distribute rewards though if the payout is zero.
-        if (validator_reward.value() > 0) \{
-            let validator_address = validator.iota_address();
-            let rewards_stake = validator.request_add_stake(validator_reward, validator_address, ctx);
-            transfer::public_transfer(rewards_stake, validator_address);
-        } else \{
-            validator_reward.destroy_zero();
-        };
-
-        // Add rewards to stake staking pool to auto compound for stakers.
-        validator.deposit_stake_rewards(staker_reward);
-        i = i + 1;
-    }
-}
-
- - - -
- - - -## Function `emit_validator_epoch_events` - -Emit events containing information of each validator for the epoch, -including stakes, rewards, performance, etc. - - -

-fun emit_validator_epoch_events(new_epoch: u64, vs: &vector<validator::Validator>, pool_staking_reward_amounts: &vector<u64>, report_records: &vec_map::VecMap<address, vec_set::VecSet<address>>, slashed_validators: &vector<address>)
-
- - - -
-Implementation - - -

-fun emit_validator_epoch_events(
-    new_epoch: u64,
-    vs: &vector<Validator>,
-    pool_staking_reward_amounts: &vector<u64>,
-    report_records: &VecMap<address, VecSet<address>>,
-    slashed_validators: &vector<address>,
-) \{
-    let num_validators = vs.length();
-    let mut i = 0;
-    while (i < num_validators) \{
-        let v = &vs[i];
-        let validator_address = v.iota_address();
-        let tallying_rule_reporters =
-            if (report_records.contains(&validator_address)) \{
-                report_records[&validator_address].into_keys()
-            } else \{
-                vector[]
-            };
-        let tallying_rule_global_score =
-            if (slashed_validators.contains(&validator_address)) 0
-            else 1;
-        event::emit(
-            ValidatorEpochInfoEventV2 \{
-                epoch: new_epoch,
-                validator_address,
-                reference_gas_survey_quote: v.gas_price(),
-                stake: v.total_stake_amount(),
-                voting_power: v.voting_power(),
-                commission_rate: v.commission_rate(),
-                pool_staking_reward: pool_staking_reward_amounts[i],
-                pool_token_exchange_rate: v.pool_token_exchange_rate_at_epoch(new_epoch),
-                tallying_rule_reporters,
-                tallying_rule_global_score,
-            }
-        );
-        i = i + 1;
-    }
-}
-
- - - -
- - - -## Function `sum_voting_power_by_addresses` - -Sum up the total stake of a given list of validator addresses. - - -

-public fun sum_voting_power_by_addresses(vs: &vector<validator::Validator>, addresses: &vector<address>): u64
-
- - - -
-Implementation - - -

-public fun sum_voting_power_by_addresses(vs: &vector<Validator>, addresses: &vector<address>): u64 \{
-    let mut sum = 0;
-    let mut i = 0;
-    let length = addresses.length();
-    while (i < length) \{
-        let validator = get_validator_ref(vs, addresses[i]);
-        sum = sum + validator.voting_power();
-        i = i + 1;
-    };
-    sum
-}
-
- - - -
- - - -## Function `active_validators` - -Return the active validators in -self - - -

-public fun active_validators(self: &validator_set::ValidatorSet): &vector<validator::Validator>
-
- - - -
-Implementation - - -

-public fun active_validators(self: &ValidatorSet): &vector<Validator> \{
-    &self.active_validators
-}
-
- - - -
- - - -## Function `is_validator_candidate` - -Returns true if the -addr is a validator candidate. - - -

-public fun is_validator_candidate(self: &validator_set::ValidatorSet, addr: address): bool
-
- - - -
-Implementation - - -

-public fun is_validator_candidate(self: &ValidatorSet, addr: address): bool \{
-    self.validator_candidates.contains(addr)
-}
-
- - - -
- - - -## Function `is_inactive_validator` - -Returns true if the staking pool identified by -staking_pool_id is of an inactive validator. - - -

-public fun is_inactive_validator(self: &validator_set::ValidatorSet, staking_pool_id: object::ID): bool
-
- - - -
-Implementation - - -

-public fun is_inactive_validator(self: &ValidatorSet, staking_pool_id: ID): bool \{
-    self.inactive_validators.contains(staking_pool_id)
-}
-
- - - -
- - - -## Function `active_validator_addresses` - - - -

-public(friend) fun active_validator_addresses(self: &validator_set::ValidatorSet): vector<address>
-
- - - -
-Implementation - - -

-public(package) fun active_validator_addresses(self: &ValidatorSet): vector<address> \{
-    let vs = &self.active_validators;
-    let mut res = vector[];
-    let mut i = 0;
-    let length = vs.length();
-    while (i < length) \{
-        let validator_address = vs[i].iota_address();
-        res.push_back(validator_address);
-        i = i + 1;
-    };
-    res
-}
-
- - - -
diff --git a/crates/iota-framework/docs/iota-system/validator_wrapper.mdx b/crates/iota-framework/docs/iota-system/validator_wrapper.mdx deleted file mode 100644 index faf70ad250c..00000000000 --- a/crates/iota-framework/docs/iota-system/validator_wrapper.mdx +++ /dev/null @@ -1,208 +0,0 @@ ---- -title: Module `0x3::validator_wrapper` ---- -import Link from '@docusaurus/Link'; - - - - -- [Struct `ValidatorWrapper`](#0x3_validator_wrapper_ValidatorWrapper) -- [Constants](#@Constants_0) -- [Function `create_v1`](#0x3_validator_wrapper_create_v1) -- [Function `load_validator_maybe_upgrade`](#0x3_validator_wrapper_load_validator_maybe_upgrade) -- [Function `destroy`](#0x3_validator_wrapper_destroy) -- [Function `upgrade_to_latest`](#0x3_validator_wrapper_upgrade_to_latest) -- [Function `version`](#0x3_validator_wrapper_version) - - -

-use 0x2::tx_context;
-use 0x2::versioned;
-use 0x3::validator;
-
- - - - - -## Struct `ValidatorWrapper` - - - -

-struct ValidatorWrapper has store
-
- - - -
-Fields - - -
-
- -inner: versioned::Versioned -
-
- -
-
- - -
- - - -## Constants - - - - - - -

-const EInvalidVersion: u64 = 0;
-
- - - - - -## Function `create_v1` - - - -

-public(friend) fun create_v1(validator: validator::Validator, ctx: &mut tx_context::TxContext): validator_wrapper::ValidatorWrapper
-
- - - -
-Implementation - - -

-public(package) fun create_v1(validator: Validator, ctx: &mut TxContext): ValidatorWrapper \{
-    ValidatorWrapper \{
-        inner: versioned::create(1, validator, ctx)
-    }
-}
-
- - - -
- - - -## Function `load_validator_maybe_upgrade` - -This function should always return the latest supported version. -If the inner version is old, we upgrade it lazily in-place. - - -

-public(friend) fun load_validator_maybe_upgrade(self: &mut validator_wrapper::ValidatorWrapper): &mut validator::Validator
-
- - - -
-Implementation - - -

-public(package) fun load_validator_maybe_upgrade(self: &mut ValidatorWrapper): &mut Validator \{
-    upgrade_to_latest(self);
-    versioned::load_value_mut(&mut self.inner)
-}
-
- - - -
- - - -## Function `destroy` - -Destroy the wrapper and retrieve the inner validator object. - - -

-public(friend) fun destroy(self: validator_wrapper::ValidatorWrapper): validator::Validator
-
- - - -
-Implementation - - -

-public(package) fun destroy(self: ValidatorWrapper): Validator \{
-    upgrade_to_latest(&self);
-    let ValidatorWrapper \{ inner } = self;
-    versioned::destroy(inner)
-}
-
- - - -
- - - -## Function `upgrade_to_latest` - - - -

-fun upgrade_to_latest(self: &validator_wrapper::ValidatorWrapper)
-
- - - -
-Implementation - - -

-fun upgrade_to_latest(self: &ValidatorWrapper) \{
-    let version = version(self);
-    // TODO: When new versions are added, we need to explicitly upgrade here.
-    assert!(version == 1, EInvalidVersion);
-}
-
- - - -
- - - -## Function `version` - - - -

-fun version(self: &validator_wrapper::ValidatorWrapper): u64
-
- - - -
-Implementation - - -

-fun version(self: &ValidatorWrapper): u64 \{
-    versioned::version(&self.inner)
-}
-
- - - -
diff --git a/crates/iota-framework/docs/iota-system/voting_power.mdx b/crates/iota-framework/docs/iota-system/voting_power.mdx deleted file mode 100644 index 3832ff99f82..00000000000 --- a/crates/iota-framework/docs/iota-system/voting_power.mdx +++ /dev/null @@ -1,546 +0,0 @@ ---- -title: Module `0x3::voting_power` ---- -import Link from '@docusaurus/Link'; - - - - -- [Struct `VotingPowerInfo`](#0x3_voting_power_VotingPowerInfo) -- [Struct `VotingPowerInfoV2`](#0x3_voting_power_VotingPowerInfoV2) -- [Constants](#@Constants_0) -- [Function `set_voting_power`](#0x3_voting_power_set_voting_power) -- [Function `init_voting_power_info`](#0x3_voting_power_init_voting_power_info) -- [Function `total_stake`](#0x3_voting_power_total_stake) -- [Function `insert`](#0x3_voting_power_insert) -- [Function `adjust_voting_power`](#0x3_voting_power_adjust_voting_power) -- [Function `update_voting_power`](#0x3_voting_power_update_voting_power) -- [Function `check_invariants`](#0x3_voting_power_check_invariants) -- [Function `total_voting_power`](#0x3_voting_power_total_voting_power) -- [Function `quorum_threshold`](#0x3_voting_power_quorum_threshold) - - -

-use 0x1::vector;
-use 0x2::math;
-use 0x3::validator;
-
- - - - - -## Struct `VotingPowerInfo` - -Deprecated. Use VotingPowerInfoV2 instead. - - -

-struct VotingPowerInfo has drop
-
- - - -
-Fields - - -
-
- -validator_index: u64 -
-
- -
-
- -voting_power: u64 -
-
- -
-
- - -
- - - -## Struct `VotingPowerInfoV2` - - - -

-struct VotingPowerInfoV2 has drop
-
- - - -
-Fields - - -
-
- -validator_index: u64 -
-
- -
-
- -voting_power: u64 -
-
- -
-
- -stake: u64 -
-
- -
-
- - -
- - - -## Constants - - - - - - -

-const EInvalidVotingPower: u64 = 4;
-
- - - - - - - -

-const ERelativePowerMismatch: u64 = 2;
-
- - - - - - - -

-const ETotalPowerMismatch: u64 = 1;
-
- - - - - - - -

-const EVotingPowerOverThreshold: u64 = 3;
-
- - - - - - - -

-const MAX_VOTING_POWER: u64 = 1000;
-
- - - - - -Quorum threshold for our fixed voting power--any message signed by this much voting power can be trusted -up to BFT assumptions - - -

-const QUORUM_THRESHOLD: u64 = 6667;
-
- - - - - -Set total_voting_power as 10_000 by convention. Individual voting powers can be interpreted -as easily understandable basis points (e.g., voting_power: 100 = 1%, voting_power: 1 = 0.01%) rather than -opaque quantities whose meaning changes from epoch to epoch as the total amount staked shifts. -Fixing the total voting power allows clients to hardcode the quorum threshold and total_voting power rather -than recomputing these. - - -

-const TOTAL_VOTING_POWER: u64 = 10000;
-
- - - - - -## Function `set_voting_power` - -Set the voting power of all validators. -Each validator's voting power is initialized using their stake. We then attempt to cap their voting power -at -MAX_VOTING_POWER. If -MAX_VOTING_POWER is not a feasible cap, we pick the lowest possible cap. - - -

-public(friend) fun set_voting_power(validators: &mut vector<validator::Validator>)
-
- - - -
-Implementation - - -

-public(package) fun set_voting_power(validators: &mut vector<Validator>) \{
-    // If threshold_pct is too small, it's possible that even when all validators reach the threshold we still don't
-    // have 100%. So we bound the threshold_pct to be always enough to find a solution.
-    let threshold = math::min(
-        TOTAL_VOTING_POWER,
-        math::max(MAX_VOTING_POWER, divide_and_round_up(TOTAL_VOTING_POWER, validators.length())),
-    );
-    let (mut info_list, remaining_power) = init_voting_power_info(validators, threshold);
-    adjust_voting_power(&mut info_list, threshold, remaining_power);
-    update_voting_power(validators, info_list);
-    check_invariants(validators);
-}
-
- - - -
- - - -## Function `init_voting_power_info` - -Create the initial voting power of each validator, set using their stake, but capped using threshold. -We also perform insertion sort while creating the voting power list, by maintaining the list in -descending order using voting power. -Anything beyond the threshold is added to the remaining_power, which is also returned. - - -

-fun init_voting_power_info(validators: &vector<validator::Validator>, threshold: u64): (vector<voting_power::VotingPowerInfoV2>, u64)
-
- - - -
-Implementation - - -

-fun init_voting_power_info(
-    validators: &vector<Validator>,
-    threshold: u64,
-): (vector<VotingPowerInfoV2>, u64) \{
-    let total_stake = total_stake(validators);
-    let mut i = 0;
-    let len = validators.length();
-    let mut total_power = 0;
-    let mut result = vector[];
-    while (i < len) \{
-        let validator = &validators[i];
-        let stake = validator.total_stake();
-        let adjusted_stake = stake as u128 * (TOTAL_VOTING_POWER as u128) / (total_stake as u128);
-        let voting_power = math::min(adjusted_stake as u64, threshold);
-        let info = VotingPowerInfoV2 \{
-            validator_index: i,
-            voting_power,
-            stake,
-        };
-        insert(&mut result, info);
-        total_power = total_power + voting_power;
-        i = i + 1;
-    };
-    (result, TOTAL_VOTING_POWER - total_power)
-}
-
- - - -
- - - -## Function `total_stake` - -Sum up the total stake of all validators. - - -

-fun total_stake(validators: &vector<validator::Validator>): u64
-
- - - -
-Implementation - - -

-fun total_stake(validators: &vector<Validator>): u64 \{
-    let mut i = 0;
-    let len = validators.length();
-    let mut total_stake =0 ;
-    while (i < len) \{
-        total_stake = total_stake + validators[i].total_stake();
-        i = i + 1;
-    };
-    total_stake
-}
-
- - - -
- - - -## Function `insert` - -Insert -new_info to -info_list as part of insertion sort, such that -info_list is always sorted -using stake, in descending order. - - -

-fun insert(info_list: &mut vector<voting_power::VotingPowerInfoV2>, new_info: voting_power::VotingPowerInfoV2)
-
- - - -
-Implementation - - -

-fun insert(info_list: &mut vector<VotingPowerInfoV2>, new_info: VotingPowerInfoV2) \{
-    let mut i = 0;
-    let len = info_list.length();
-    while (i < len && info_list[i].stake > new_info.stake) \{
-        i = i + 1;
-    };
-    info_list.insert(new_info, i);
-}
-
- - - -
- - - -## Function `adjust_voting_power` - -Distribute remaining_power to validators that are not capped at threshold. - - -

-fun adjust_voting_power(info_list: &mut vector<voting_power::VotingPowerInfoV2>, threshold: u64, remaining_power: u64)
-
- - - -
-Implementation - - -

-fun adjust_voting_power(info_list: &mut vector<VotingPowerInfoV2>, threshold: u64, mut remaining_power: u64) \{
-    let mut i = 0;
-    let len = info_list.length();
-    while (i < len && remaining_power > 0) \{
-        let v = &mut info_list[i];
-        // planned is the amount of extra power we want to distribute to this validator.
-        let planned = divide_and_round_up(remaining_power, len - i);
-        // target is the targeting power this validator will reach, capped by threshold.
-        let target = math::min(threshold, v.voting_power + planned);
-        // actual is the actual amount of power we will be distributing to this validator.
-        let actual = math::min(remaining_power, target - v.voting_power);
-        v.voting_power = v.voting_power + actual;
-        assert!(v.voting_power <= threshold, EVotingPowerOverThreshold);
-        remaining_power = remaining_power - actual;
-        i = i + 1;
-    };
-    assert!(remaining_power == 0, ETotalPowerMismatch);
-}
-
- - - -
- - - -## Function `update_voting_power` - -Update validators with the decided voting power. - - -

-fun update_voting_power(validators: &mut vector<validator::Validator>, info_list: vector<voting_power::VotingPowerInfoV2>)
-
- - - -
-Implementation - - -

-fun update_voting_power(validators: &mut vector<Validator>, mut info_list: vector<VotingPowerInfoV2>) \{
-    while (!info_list.is_empty()) \{
-        let VotingPowerInfoV2 \{
-            validator_index,
-            voting_power,
-            stake: _,
-        } = info_list.pop_back();
-        let v = &mut validators[validator_index];
-        v.set_voting_power(voting_power);
-    };
-    info_list.destroy_empty();
-}
-
- - - -
- - - -## Function `check_invariants` - -Check a few invariants that must hold after setting the voting power. - - -

-fun check_invariants(v: &vector<validator::Validator>)
-
- - - -
-Implementation - - -

-fun check_invariants(v: &vector<Validator>) \{
-    // First check that the total voting power must be TOTAL_VOTING_POWER.
-    let mut i = 0;
-    let len = v.length();
-    let mut total = 0;
-    while (i < len) \{
-        let voting_power = v[i].voting_power();
-        assert!(voting_power > 0, EInvalidVotingPower);
-        total = total + voting_power;
-        i = i + 1;
-    };
-    assert!(total == TOTAL_VOTING_POWER, ETotalPowerMismatch);
-
-    // Second check that if validator A's stake is larger than B's stake, A's voting power must be no less
-    // than B's voting power; similarly, if A's stake is less than B's stake, A's voting power must be no larger
-    // than B's voting power.
-    let mut a = 0;
-    while (a < len) \{
-        let mut b = a + 1;
-        while (b < len) \{
-            let validator_a = &v[a];
-            let validator_b = &v[b];
-            let stake_a = validator_a.total_stake();
-            let stake_b = validator_b.total_stake();
-            let power_a = validator_a.voting_power();
-            let power_b = validator_b.voting_power();
-            if (stake_a > stake_b) \{
-                assert!(power_a >= power_b, ERelativePowerMismatch);
-            };
-            if (stake_a < stake_b) \{
-                assert!(power_a <= power_b, ERelativePowerMismatch);
-            };
-            b = b + 1;
-        };
-        a = a + 1;
-    }
-}
-
- - - -
- - - -## Function `total_voting_power` - -Return the (constant) total voting power - - -

-public fun total_voting_power(): u64
-
- - - -
-Implementation - - -

-public fun total_voting_power(): u64 \{
-    TOTAL_VOTING_POWER
-}
-
- - - -
- - - -## Function `quorum_threshold` - -Return the (constant) quorum threshold - - -

-public fun quorum_threshold(): u64
-
- - - -
-Implementation - - -

-public fun quorum_threshold(): u64 \{
-    QUORUM_THRESHOLD
-}
-
- - - -
diff --git a/crates/iota-framework/docs/move-stdlib/address.mdx b/crates/iota-framework/docs/move-stdlib/address.mdx deleted file mode 100644 index 01cfe672f3e..00000000000 --- a/crates/iota-framework/docs/move-stdlib/address.mdx +++ /dev/null @@ -1,45 +0,0 @@ ---- -title: Module `0x1::address` ---- -import Link from '@docusaurus/Link'; - - -Provides a way to get address length since it's a -platform-specific parameter. - - -- [Function `length`](#0x1_address_length) - - -

-
- - - - - -## Function `length` - -Should be converted to a native function. -Current implementation only works for Iota. - - -

-public fun length(): u64
-
- - - -
-Implementation - - -

-public fun length(): u64 \{
-    32
-}
-
- - - -
diff --git a/crates/iota-framework/docs/move-stdlib/ascii.mdx b/crates/iota-framework/docs/move-stdlib/ascii.mdx deleted file mode 100644 index 936ec944a93..00000000000 --- a/crates/iota-framework/docs/move-stdlib/ascii.mdx +++ /dev/null @@ -1,484 +0,0 @@ ---- -title: Module `0x1::ascii` ---- -import Link from '@docusaurus/Link'; - - -The -ASCII module defines basic string and char newtypes in Move that verify -that characters are valid ASCII, and that strings consist of only valid ASCII characters. - - -- [Struct `String`](#0x1_ascii_String) -- [Struct `Char`](#0x1_ascii_Char) -- [Constants](#@Constants_0) -- [Function `char`](#0x1_ascii_char) -- [Function `string`](#0x1_ascii_string) -- [Function `try_string`](#0x1_ascii_try_string) -- [Function `all_characters_printable`](#0x1_ascii_all_characters_printable) -- [Function `push_char`](#0x1_ascii_push_char) -- [Function `pop_char`](#0x1_ascii_pop_char) -- [Function `length`](#0x1_ascii_length) -- [Function `as_bytes`](#0x1_ascii_as_bytes) -- [Function `into_bytes`](#0x1_ascii_into_bytes) -- [Function `byte`](#0x1_ascii_byte) -- [Function `is_valid_char`](#0x1_ascii_is_valid_char) -- [Function `is_printable_char`](#0x1_ascii_is_printable_char) - - -

-use 0x1::option;
-
- - - - - -## Struct `String` - -The -String struct holds a vector of bytes that all represent -valid ASCII characters. Note that these ASCII characters may not all -be printable. To determine if a -String contains only "printable" -characters you should use the -all_characters_printable predicate -defined in this module. - - -

-struct String has copy, drop, store
-
- - - -
-Fields - - -
-
- -bytes: vector<u8> -
-
- -
-
- - -
- - - -## Struct `Char` - -An ASCII character. - - -

-struct Char has copy, drop, store
-
- - - -
-Fields - - -
-
- -byte: u8 -
-
- -
-
- - -
- - - -## Constants - - - - -An invalid ASCII character was encountered when creating an ASCII string. - - -

-const EINVALID_ASCII_CHARACTER: u64 = 65536;
-
- - - - - -## Function `char` - -Convert a -byte into a -Char that is checked to make sure it is valid ASCII. - - -

-public fun char(byte: u8): ascii::Char
-
- - - -
-Implementation - - -

-public fun char(byte: u8): Char \{
-    assert!(is_valid_char(byte), EINVALID_ASCII_CHARACTER);
-    Char \{ byte }
-}
-
- - - -
- - - -## Function `string` - -Convert a vector of bytes -bytes into an -String. Aborts if - -bytes contains non-ASCII characters. - - -

-public fun string(bytes: vector<u8>): ascii::String
-
- - - -
-Implementation - - -

-public fun string(bytes: vector<u8>): String \{
-   let x = try_string(bytes);
-   assert!(x.is_some(), EINVALID_ASCII_CHARACTER);
-   x.destroy_some()
-}
-
- - - -
- - - -## Function `try_string` - -Convert a vector of bytes -bytes into an -String. Returns - -Some(<ascii_string>) if the -bytes contains all valid ASCII -characters. Otherwise returns -None. - - -

-public fun try_string(bytes: vector<u8>): option::Option<ascii::String>
-
- - - -
-Implementation - - -

-public fun try_string(bytes: vector<u8>): Option<String> \{
-    let len = bytes.length();
-    let mut i = 0;
-    while (i < len) \{
-        let possible_byte = bytes[i];
-        if (!is_valid_char(possible_byte)) return option::none();
-        i = i + 1;
-    };
-    option::some(String \{ bytes })
-}
-
- - - -
- - - -## Function `all_characters_printable` - -Returns -true if all characters in -string are printable characters -Returns -false otherwise. Not all -Strings are printable strings. - - -

-public fun all_characters_printable(string: &ascii::String): bool
-
- - - -
-Implementation - - -

-public fun all_characters_printable(string: &String): bool \{
-    let len = string.bytes.length();
-    let mut i = 0;
-    while (i < len) \{
-        let byte = string.bytes[i];
-        if (!is_printable_char(byte)) return false;
-        i = i + 1;
-    };
-    true
-}
-
- - - -
- - - -## Function `push_char` - - - -

-public fun push_char(string: &mut ascii::String, char: ascii::Char)
-
- - - -
-Implementation - - -

-public fun push_char(string: &mut String, char: Char) \{
-    string.bytes.push_back(char.byte);
-}
-
- - - -
- - - -## Function `pop_char` - - - -

-public fun pop_char(string: &mut ascii::String): ascii::Char
-
- - - -
-Implementation - - -

-public fun pop_char(string: &mut String): Char \{
-    Char \{ byte: string.bytes.pop_back() }
-}
-
- - - -
- - - -## Function `length` - - - -

-public fun length(string: &ascii::String): u64
-
- - - -
-Implementation - - -

-public fun length(string: &String): u64 \{
-    string.as_bytes().length()
-}
-
- - - -
- - - -## Function `as_bytes` - -Get the inner bytes of the -string as a reference - - -

-public fun as_bytes(string: &ascii::String): &vector<u8>
-
- - - -
-Implementation - - -

-public fun as_bytes(string: &String): &vector<u8> \{
-   &string.bytes
-}
-
- - - -
- - - -## Function `into_bytes` - -Unpack the -string to get its backing bytes - - -

-public fun into_bytes(string: ascii::String): vector<u8>
-
- - - -
-Implementation - - -

-public fun into_bytes(string: String): vector<u8> \{
-   let String \{ bytes } = string;
-   bytes
-}
-
- - - -
- - - -## Function `byte` - -Unpack the -char into its underlying byte. - - -

-public fun byte(char: ascii::Char): u8
-
- - - -
-Implementation - - -

-public fun byte(char: Char): u8 \{
-   let Char \{ byte } = char;
-   byte
-}
-
- - - -
- - - -## Function `is_valid_char` - -Returns -true if -b is a valid ASCII character. Returns -false otherwise. - - -

-public fun is_valid_char(b: u8): bool
-
- - - -
-Implementation - - -

-public fun is_valid_char(b: u8): bool \{
-   b <= 0x7F
-}
-
- - - -
- - - -## Function `is_printable_char` - -Returns -true if -byte is an printable ASCII character. Returns -false otherwise. - - -

-public fun is_printable_char(byte: u8): bool
-
- - - -
-Implementation - - -

-public fun is_printable_char(byte: u8): bool \{
-   byte >= 0x20 && // Disallow metacharacters
-   byte <= 0x7E // Don't allow DEL metacharacter
-}
-
- - - -
diff --git a/crates/iota-framework/docs/move-stdlib/bcs.mdx b/crates/iota-framework/docs/move-stdlib/bcs.mdx deleted file mode 100644 index 434ebf718c8..00000000000 --- a/crates/iota-framework/docs/move-stdlib/bcs.mdx +++ /dev/null @@ -1,45 +0,0 @@ ---- -title: Module `0x1::bcs` ---- -import Link from '@docusaurus/Link'; - - -Utility for converting a Move value to its binary representation in BCS (Binary Canonical -Serialization). BCS is the binary encoding for Move resources and other non-module values -published on-chain. See https://github.com/diem/bcs#binary-canonical-serialization-bcs for more -details on BCS. - - -- [Function `to_bytes`](#0x1_bcs_to_bytes) - - -

-
- - - - - -## Function `to_bytes` - -Return the binary representation of -v in BCS (Binary Canonical Serialization) format - - -

-public fun to_bytes<MoveValue>(v: &MoveValue): vector<u8>
-
- - - -
-Implementation - - -

-native public fun to_bytes<MoveValue>(v: &MoveValue): vector<u8>;
-
- - - -
diff --git a/crates/iota-framework/docs/move-stdlib/fixed_point32.mdx b/crates/iota-framework/docs/move-stdlib/fixed_point32.mdx deleted file mode 100644 index 5650cbbfd85..00000000000 --- a/crates/iota-framework/docs/move-stdlib/fixed_point32.mdx +++ /dev/null @@ -1,345 +0,0 @@ ---- -title: Module `0x1::fixed_point32` ---- -import Link from '@docusaurus/Link'; - - -Defines a fixed-point numeric type with a 32-bit integer part and -a 32-bit fractional part. - - -- [Struct `FixedPoint32`](#0x1_fixed_point32_FixedPoint32) -- [Constants](#@Constants_0) -- [Function `multiply_u64`](#0x1_fixed_point32_multiply_u64) -- [Function `divide_u64`](#0x1_fixed_point32_divide_u64) -- [Function `create_from_rational`](#0x1_fixed_point32_create_from_rational) -- [Function `create_from_raw_value`](#0x1_fixed_point32_create_from_raw_value) -- [Function `get_raw_value`](#0x1_fixed_point32_get_raw_value) -- [Function `is_zero`](#0x1_fixed_point32_is_zero) - - -

-
- - - - - -## Struct `FixedPoint32` - -Define a fixed-point numeric type with 32 fractional bits. -This is just a u64 integer but it is wrapped in a struct to -make a unique type. This is a binary representation, so decimal -values may not be exactly representable, but it provides more -than 9 decimal digits of precision both before and after the -decimal point (18 digits total). For comparison, double precision -floating-point has less than 16 decimal digits of precision, so -be careful about using floating-point to convert these values to -decimal. - - -

-struct FixedPoint32 has copy, drop, store
-
- - - -
-Fields - - -
-
- -value: u64 -
-
- -
-
- - -
- - - -## Constants - - - - -The denominator provided was zero - - -

-const EDENOMINATOR: u64 = 65537;
-
- - - - - -The quotient value would be too large to be held in a -u64 - - -

-const EDIVISION: u64 = 131074;
-
- - - - - -A division by zero was encountered - - -

-const EDIVISION_BY_ZERO: u64 = 65540;
-
- - - - - -The multiplied value would be too large to be held in a -u64 - - -

-const EMULTIPLICATION: u64 = 131075;
-
- - - - - -The computed ratio when converting to a -FixedPoint32 would be unrepresentable - - -

-const ERATIO_OUT_OF_RANGE: u64 = 131077;
-
- - - - - -> TODO: This is a basic constant and should be provided somewhere centrally in the framework. - - -

-const MAX_U64: u128 = 18446744073709551615;
-
- - - - - -## Function `multiply_u64` - -Multiply a u64 integer by a fixed-point number, truncating any -fractional part of the product. This will abort if the product -overflows. - - -

-public fun multiply_u64(val: u64, multiplier: fixed_point32::FixedPoint32): u64
-
- - - -
-Implementation - - -

-public fun multiply_u64(val: u64, multiplier: FixedPoint32): u64 \{
-    // The product of two 64 bit values has 128 bits, so perform the
-    // multiplication with u128 types and keep the full 128 bit product
-    // to avoid losing accuracy.
-    let unscaled_product = val as u128 * (multiplier.value as u128);
-    // The unscaled product has 32 fractional bits (from the multiplier)
-    // so rescale it by shifting away the low bits.
-    let product = unscaled_product >> 32;
-    // Check whether the value is too large.
-    assert!(product <= MAX_U64, EMULTIPLICATION);
-    product as u64
-}
-
- - - -
- - - -## Function `divide_u64` - -Divide a u64 integer by a fixed-point number, truncating any -fractional part of the quotient. This will abort if the divisor -is zero or if the quotient overflows. - - -

-public fun divide_u64(val: u64, divisor: fixed_point32::FixedPoint32): u64
-
- - - -
-Implementation - - -

-public fun divide_u64(val: u64, divisor: FixedPoint32): u64 \{
-    // Check for division by zero.
-    assert!(divisor.value != 0, EDIVISION_BY_ZERO);
-    // First convert to 128 bits and then shift left to
-    // add 32 fractional zero bits to the dividend.
-    let scaled_value = val as u128 << 32;
-    let quotient = scaled_value / (divisor.value as u128);
-    // Check whether the value is too large.
-    assert!(quotient <= MAX_U64, EDIVISION);
-    // the value may be too large, which will cause the cast to fail
-    // with an arithmetic error.
-    quotient as u64
-}
-
- - - -
- - - -## Function `create_from_rational` - -Create a fixed-point value from a rational number specified by its -numerator and denominator. Calling this function should be preferred -for using -Self::create_from_raw_value which is also available. -This will abort if the denominator is zero. It will also -abort if the numerator is nonzero and the ratio is not in the range -2^-32 .. 2^32-1. When specifying decimal fractions, be careful about -rounding errors: if you round to display N digits after the decimal -point, you can use a denominator of 10^N to avoid numbers where the -very small imprecision in the binary representation could change the -rounding, e.g., 0.0125 will round down to 0.012 instead of up to 0.013. - - -

-public fun create_from_rational(numerator: u64, denominator: u64): fixed_point32::FixedPoint32
-
- - - -
-Implementation - - -

-public fun create_from_rational(numerator: u64, denominator: u64): FixedPoint32 \{
-    // If the denominator is zero, this will abort.
-    // Scale the numerator to have 64 fractional bits and the denominator
-    // to have 32 fractional bits, so that the quotient will have 32
-    // fractional bits.
-    let scaled_numerator = numerator as u128 << 64;
-    let scaled_denominator = denominator as u128 << 32;
-    assert!(scaled_denominator != 0, EDENOMINATOR);
-    let quotient = scaled_numerator / scaled_denominator;
-    assert!(quotient != 0 || numerator == 0, ERATIO_OUT_OF_RANGE);
-    // Return the quotient as a fixed-point number. We first need to check whether the cast
-    // can succeed.
-    assert!(quotient <= MAX_U64, ERATIO_OUT_OF_RANGE);
-    FixedPoint32 \{ value: quotient as u64 }
-}
-
- - - -
- - - -## Function `create_from_raw_value` - -Create a fixedpoint value from a raw value. - - -

-public fun create_from_raw_value(value: u64): fixed_point32::FixedPoint32
-
- - - -
-Implementation - - -

-public fun create_from_raw_value(value: u64): FixedPoint32 \{
-    FixedPoint32 \{ value }
-}
-
- - - -
- - - -## Function `get_raw_value` - -Accessor for the raw u64 value. Other less common operations, such as -adding or subtracting FixedPoint32 values, can be done using the raw -values directly. - - -

-public fun get_raw_value(num: fixed_point32::FixedPoint32): u64
-
- - - -
-Implementation - - -

-public fun get_raw_value(num: FixedPoint32): u64 \{
-    num.value
-}
-
- - - -
- - - -## Function `is_zero` - -Returns true if the ratio is zero. - - -

-public fun is_zero(num: fixed_point32::FixedPoint32): bool
-
- - - -
-Implementation - - -

-public fun is_zero(num: FixedPoint32): bool \{
-    num.value == 0
-}
-
- - - -
diff --git a/crates/iota-framework/docs/move-stdlib/option.mdx b/crates/iota-framework/docs/move-stdlib/option.mdx deleted file mode 100644 index 5cffb0bedef..00000000000 --- a/crates/iota-framework/docs/move-stdlib/option.mdx +++ /dev/null @@ -1,646 +0,0 @@ ---- -title: Module `0x1::option` ---- -import Link from '@docusaurus/Link'; - - -This module defines the Option type and its methods to represent and handle an optional value. - - -- [Struct `Option`](#0x1_option_Option) -- [Constants](#@Constants_0) -- [Function `none`](#0x1_option_none) -- [Function `some`](#0x1_option_some) -- [Function `is_none`](#0x1_option_is_none) -- [Function `is_some`](#0x1_option_is_some) -- [Function `contains`](#0x1_option_contains) -- [Function `borrow`](#0x1_option_borrow) -- [Function `borrow_with_default`](#0x1_option_borrow_with_default) -- [Function `get_with_default`](#0x1_option_get_with_default) -- [Function `fill`](#0x1_option_fill) -- [Function `extract`](#0x1_option_extract) -- [Function `borrow_mut`](#0x1_option_borrow_mut) -- [Function `swap`](#0x1_option_swap) -- [Function `swap_or_fill`](#0x1_option_swap_or_fill) -- [Function `destroy_with_default`](#0x1_option_destroy_with_default) -- [Function `destroy_some`](#0x1_option_destroy_some) -- [Function `destroy_none`](#0x1_option_destroy_none) -- [Function `to_vec`](#0x1_option_to_vec) - - -

-use 0x1::vector;
-
- - - - - -## Struct `Option` - -Abstraction of a value that may or may not be present. Implemented with a vector of size -zero or one because Move bytecode does not have ADTs. - - -

-struct Option<Element> has copy, drop, store
-
- - - -
-Fields - - -
-
- -vec: vector<Element> -
-
- -
-
- - -
- - - -## Constants - - - - -The -Option is in an invalid state for the operation attempted. -The -Option is -Some while it should be -None. - - -

-const EOPTION_IS_SET: u64 = 262144;
-
- - - - - -The -Option is in an invalid state for the operation attempted. -The -Option is -None while it should be -Some. - - -

-const EOPTION_NOT_SET: u64 = 262145;
-
- - - - - -## Function `none` - -Return an empty -Option - - -

-public fun none<Element>(): option::Option<Element>
-
- - - -
-Implementation - - -

-public fun none<Element>(): Option<Element> \{
-    Option \{ vec: vector::empty() }
-}
-
- - - -
- - - -## Function `some` - -Return an -Option containing -e - - -

-public fun some<Element>(e: Element): option::Option<Element>
-
- - - -
-Implementation - - -

-public fun some<Element>(e: Element): Option<Element> \{
-    Option \{ vec: vector::singleton(e) }
-}
-
- - - -
- - - -## Function `is_none` - -Return true if -t does not hold a value - - -

-public fun is_none<Element>(t: &option::Option<Element>): bool
-
- - - -
-Implementation - - -

-public fun is_none<Element>(t: &Option<Element>): bool \{
-    t.vec.is_empty()
-}
-
- - - -
- - - -## Function `is_some` - -Return true if -t holds a value - - -

-public fun is_some<Element>(t: &option::Option<Element>): bool
-
- - - -
-Implementation - - -

-public fun is_some<Element>(t: &Option<Element>): bool \{
-    !t.vec.is_empty()
-}
-
- - - -
- - - -## Function `contains` - -Return true if the value in -t is equal to -e_ref -Always returns -false if -t does not hold a value - - -

-public fun contains<Element>(t: &option::Option<Element>, e_ref: &Element): bool
-
- - - -
-Implementation - - -

-public fun contains<Element>(t: &Option<Element>, e_ref: &Element): bool \{
-    t.vec.contains(e_ref)
-}
-
- - - -
- - - -## Function `borrow` - -Return an immutable reference to the value inside -t -Aborts if -t does not hold a value - - -

-public fun borrow<Element>(t: &option::Option<Element>): &Element
-
- - - -
-Implementation - - -

-public fun borrow<Element>(t: &Option<Element>): &Element \{
-    assert!(t.is_some(), EOPTION_NOT_SET);
-    &t.vec[0]
-}
-
- - - -
- - - -## Function `borrow_with_default` - -Return a reference to the value inside -t if it holds one -Return -default_ref if -t does not hold a value - - -

-public fun borrow_with_default<Element>(t: &option::Option<Element>, default_ref: &Element): &Element
-
- - - -
-Implementation - - -

-public fun borrow_with_default<Element>(t: &Option<Element>, default_ref: &Element): &Element \{
-    let vec_ref = &t.vec;
-    if (vec_ref.is_empty()) default_ref
-    else &vec_ref[0]
-}
-
- - - -
- - - -## Function `get_with_default` - -Return the value inside -t if it holds one -Return -default if -t does not hold a value - - -

-public fun get_with_default<Element: copy, drop>(t: &option::Option<Element>, default: Element): Element
-
- - - -
-Implementation - - -

-public fun get_with_default<Element: copy + drop>(
-    t: &Option<Element>,
-    default: Element,
-): Element \{
-    let vec_ref = &t.vec;
-    if (vec_ref.is_empty()) default
-    else vec_ref[0]
-}
-
- - - -
- - - -## Function `fill` - -Convert the none option -t to a some option by adding -e. -Aborts if -t already holds a value - - -

-public fun fill<Element>(t: &mut option::Option<Element>, e: Element)
-
- - - -
-Implementation - - -

-public fun fill<Element>(t: &mut Option<Element>, e: Element) \{
-    let vec_ref = &mut t.vec;
-    if (vec_ref.is_empty()) vec_ref.push_back(e)
-    else abort EOPTION_IS_SET
-}
-
- - - -
- - - -## Function `extract` - -Convert a -some option to a -none by removing and returning the value stored inside -t -Aborts if -t does not hold a value - - -

-public fun extract<Element>(t: &mut option::Option<Element>): Element
-
- - - -
-Implementation - - -

-public fun extract<Element>(t: &mut Option<Element>): Element \{
-    assert!(t.is_some(), EOPTION_NOT_SET);
-    t.vec.pop_back()
-}
-
- - - -
- - - -## Function `borrow_mut` - -Return a mutable reference to the value inside -t -Aborts if -t does not hold a value - - -

-public fun borrow_mut<Element>(t: &mut option::Option<Element>): &mut Element
-
- - - -
-Implementation - - -

-public fun borrow_mut<Element>(t: &mut Option<Element>): &mut Element \{
-    assert!(t.is_some(), EOPTION_NOT_SET);
-    &mut t.vec[0]
-}
-
- - - -
- - - -## Function `swap` - -Swap the old value inside -t with -e and return the old value -Aborts if -t does not hold a value - - -

-public fun swap<Element>(t: &mut option::Option<Element>, e: Element): Element
-
- - - -
-Implementation - - -

-public fun swap<Element>(t: &mut Option<Element>, e: Element): Element \{
-    assert!(t.is_some(), EOPTION_NOT_SET);
-    let vec_ref = &mut t.vec;
-    let old_value = vec_ref.pop_back();
-    vec_ref.push_back(e);
-    old_value
-}
-
- - - -
- - - -## Function `swap_or_fill` - -Swap the old value inside -t with -e and return the old value; -or if there is no old value, fill it with -e. -Different from swap(), swap_or_fill() allows for -t not holding a value. - - -

-public fun swap_or_fill<Element>(t: &mut option::Option<Element>, e: Element): option::Option<Element>
-
- - - -
-Implementation - - -

-public fun swap_or_fill<Element>(t: &mut Option<Element>, e: Element): Option<Element> \{
-    let vec_ref = &mut t.vec;
-    let old_value = if (vec_ref.is_empty()) none()
-        else some(vec_ref.pop_back());
-    vec_ref.push_back(e);
-    old_value
-}
-
- - - -
- - - -## Function `destroy_with_default` - -Destroys -t. If -t holds a value, return it. Returns -default otherwise - - -

-public fun destroy_with_default<Element: drop>(t: option::Option<Element>, default: Element): Element
-
- - - -
-Implementation - - -

-public fun destroy_with_default<Element: drop>(t: Option<Element>, default: Element): Element \{
-    let Option \{ mut vec } = t;
-    if (vec.is_empty()) default
-    else vec.pop_back()
-}
-
- - - -
- - - -## Function `destroy_some` - -Unpack -t and return its contents -Aborts if -t does not hold a value - - -

-public fun destroy_some<Element>(t: option::Option<Element>): Element
-
- - - -
-Implementation - - -

-public fun destroy_some<Element>(t: Option<Element>): Element \{
-    assert!(t.is_some(), EOPTION_NOT_SET);
-    let Option \{ mut vec } = t;
-    let elem = vec.pop_back();
-    vec.destroy_empty();
-    elem
-}
-
- - - -
- - - -## Function `destroy_none` - -Unpack -t -Aborts if -t holds a value - - -

-public fun destroy_none<Element>(t: option::Option<Element>)
-
- - - -
-Implementation - - -

-public fun destroy_none<Element>(t: Option<Element>) \{
-    assert!(t.is_none(), EOPTION_IS_SET);
-    let Option \{ vec } = t;
-    vec.destroy_empty()
-}
-
- - - -
- - - -## Function `to_vec` - -Convert -t into a vector of length 1 if it is -Some, -and an empty vector otherwise - - -

-public fun to_vec<Element>(t: option::Option<Element>): vector<Element>
-
- - - -
-Implementation - - -

-public fun to_vec<Element>(t: Option<Element>): vector<Element> \{
-    let Option \{ vec } = t;
-    vec
-}
-
- - - -
diff --git a/crates/iota-framework/docs/move-stdlib/string.mdx b/crates/iota-framework/docs/move-stdlib/string.mdx deleted file mode 100644 index 1ca1e5701bf..00000000000 --- a/crates/iota-framework/docs/move-stdlib/string.mdx +++ /dev/null @@ -1,543 +0,0 @@ ---- -title: Module `0x1::string` ---- -import Link from '@docusaurus/Link'; - - -The -string module defines the -String type which represents UTF8 encoded strings. - - -- [Struct `String`](#0x1_string_String) -- [Constants](#@Constants_0) -- [Function `utf8`](#0x1_string_utf8) -- [Function `from_ascii`](#0x1_string_from_ascii) -- [Function `to_ascii`](#0x1_string_to_ascii) -- [Function `try_utf8`](#0x1_string_try_utf8) -- [Function `bytes`](#0x1_string_bytes) -- [Function `is_empty`](#0x1_string_is_empty) -- [Function `length`](#0x1_string_length) -- [Function `append`](#0x1_string_append) -- [Function `append_utf8`](#0x1_string_append_utf8) -- [Function `insert`](#0x1_string_insert) -- [Function `sub_string`](#0x1_string_sub_string) -- [Function `index_of`](#0x1_string_index_of) -- [Function `internal_check_utf8`](#0x1_string_internal_check_utf8) -- [Function `internal_is_char_boundary`](#0x1_string_internal_is_char_boundary) -- [Function `internal_sub_string`](#0x1_string_internal_sub_string) -- [Function `internal_index_of`](#0x1_string_internal_index_of) - - -

-use 0x1::ascii;
-use 0x1::option;
-use 0x1::vector;
-
- - - - - -## Struct `String` - -A -String holds a sequence of bytes which is guaranteed to be in utf8 format. - - -

-struct String has copy, drop, store
-
- - - -
-Fields - - -
-
- -bytes: vector<u8> -
-
- -
-
- - -
- - - -## Constants - - - - -Index out of range. - - -

-const EINVALID_INDEX: u64 = 2;
-
- - - - - -An invalid UTF8 encoding. - - -

-const EINVALID_UTF8: u64 = 1;
-
- - - - - -## Function `utf8` - -Creates a new string from a sequence of bytes. Aborts if the bytes do not represent valid utf8. - - -

-public fun utf8(bytes: vector<u8>): string::String
-
- - - -
-Implementation - - -

-public fun utf8(bytes: vector<u8>): String \{
-    assert!(internal_check_utf8(&bytes), EINVALID_UTF8);
-    String \{ bytes }
-}
-
- - - -
- - - -## Function `from_ascii` - -Convert an ASCII string to a UTF8 string - - -

-public fun from_ascii(s: ascii::String): string::String
-
- - - -
-Implementation - - -

-public fun from_ascii(s: ascii::String): String \{
-    String \{ bytes: ascii::into_bytes(s) }
-}
-
- - - -
- - - -## Function `to_ascii` - -Convert an UTF8 string to an ASCII string. -Aborts if -s is not valid ASCII - - -

-public fun to_ascii(s: string::String): ascii::String
-
- - - -
-Implementation - - -

-public fun to_ascii(s: String): ascii::String \{
-    let String \{ bytes } = s;
-    ascii::string(bytes)
-}
-
- - - -
- - - -## Function `try_utf8` - -Tries to create a new string from a sequence of bytes. - - -

-public fun try_utf8(bytes: vector<u8>): option::Option<string::String>
-
- - - -
-Implementation - - -

-public fun try_utf8(bytes: vector<u8>): Option<String> \{
-    if (internal_check_utf8(&bytes)) \{
-        option::some(String \{ bytes })
-    } else \{
-        option::none()
-    }
-}
-
- - - -
- - - -## Function `bytes` - -Returns a reference to the underlying byte vector. - - -

-public fun bytes(s: &string::String): &vector<u8>
-
- - - -
-Implementation - - -

-public fun bytes(s: &String): &vector<u8> \{
-    &s.bytes
-}
-
- - - -
- - - -## Function `is_empty` - -Checks whether this string is empty. - - -

-public fun is_empty(s: &string::String): bool
-
- - - -
-Implementation - - -

-public fun is_empty(s: &String): bool \{
-    s.bytes.is_empty()
-}
-
- - - -
- - - -## Function `length` - -Returns the length of this string, in bytes. - - -

-public fun length(s: &string::String): u64
-
- - - -
-Implementation - - -

-public fun length(s: &String): u64 \{
-    s.bytes.length()
-}
-
- - - -
- - - -## Function `append` - -Appends a string. - - -

-public fun append(s: &mut string::String, r: string::String)
-
- - - -
-Implementation - - -

-public fun append(s: &mut String, r: String) \{
-    s.bytes.append(r.bytes)
-}
-
- - - -
- - - -## Function `append_utf8` - -Appends bytes which must be in valid utf8 format. - - -

-public fun append_utf8(s: &mut string::String, bytes: vector<u8>)
-
- - - -
-Implementation - - -

-public fun append_utf8(s: &mut String, bytes: vector<u8>) \{
-    s.append(utf8(bytes))
-}
-
- - - -
- - - -## Function `insert` - -Insert the other string at the byte index in given string. The index must be at a valid utf8 char -boundary. - - -

-public fun insert(s: &mut string::String, at: u64, o: string::String)
-
- - - -
-Implementation - - -

-public fun insert(s: &mut String, at: u64, o: String) \{
-    let bytes = &s.bytes;
-    assert!(at <= bytes.length() && internal_is_char_boundary(bytes, at), EINVALID_INDEX);
-    let l = s.length();
-    let mut front = s.sub_string(0, at);
-    let end = s.sub_string(at, l);
-    front.append(o);
-    front.append(end);
-    *s = front;
-}
-
- - - -
- - - -## Function `sub_string` - -Returns a sub-string using the given byte indices, where -i is the first byte position and -j is the start -of the first byte not included (or the length of the string). The indices must be at valid utf8 char boundaries, -guaranteeing that the result is valid utf8. - - -

-public fun sub_string(s: &string::String, i: u64, j: u64): string::String
-
- - - -
-Implementation - - -

-public fun sub_string(s: &String, i: u64, j: u64): String \{
-    let bytes = &s.bytes;
-    let l = bytes.length();
-    assert!(
-        j <= l && i <= j && internal_is_char_boundary(bytes, i) && internal_is_char_boundary(bytes, j),
-        EINVALID_INDEX
-    );
-    String\{bytes: internal_sub_string(bytes, i, j)}
-}
-
- - - -
- - - -## Function `index_of` - -Computes the index of the first occurrence of a string. Returns -length(s) if no occurrence found. - - -

-public fun index_of(s: &string::String, r: &string::String): u64
-
- - - -
-Implementation - - -

-public fun index_of(s: &String, r: &String): u64 \{
-    internal_index_of(&s.bytes, &r.bytes)
-}
-
- - - -
- - - -## Function `internal_check_utf8` - - - -

-fun internal_check_utf8(v: &vector<u8>): bool
-
- - - -
-Implementation - - -

-native fun internal_check_utf8(v: &vector<u8>): bool;
-
- - - -
- - - -## Function `internal_is_char_boundary` - - - -

-fun internal_is_char_boundary(v: &vector<u8>, i: u64): bool
-
- - - -
-Implementation - - -

-native fun internal_is_char_boundary(v: &vector<u8>, i: u64): bool;
-
- - - -
- - - -## Function `internal_sub_string` - - - -

-fun internal_sub_string(v: &vector<u8>, i: u64, j: u64): vector<u8>
-
- - - -
-Implementation - - -

-native fun internal_sub_string(v: &vector<u8>, i: u64, j: u64): vector<u8>;
-
- - - -
- - - -## Function `internal_index_of` - - - -

-fun internal_index_of(v: &vector<u8>, r: &vector<u8>): u64
-
- - - -
-Implementation - - -

-native fun internal_index_of(v: &vector<u8>, r: &vector<u8>): u64;
-
- - - -
diff --git a/crates/iota-framework/docs/move-stdlib/type_name.mdx b/crates/iota-framework/docs/move-stdlib/type_name.mdx deleted file mode 100644 index ba599c052f4..00000000000 --- a/crates/iota-framework/docs/move-stdlib/type_name.mdx +++ /dev/null @@ -1,409 +0,0 @@ ---- -title: Module `0x1::type_name` ---- -import Link from '@docusaurus/Link'; - - -Functionality for converting Move types into values. Use with care! - - -- [Struct `TypeName`](#0x1_type_name_TypeName) -- [Constants](#@Constants_0) -- [Function `get`](#0x1_type_name_get) -- [Function `get_with_original_ids`](#0x1_type_name_get_with_original_ids) -- [Function `is_primitive`](#0x1_type_name_is_primitive) -- [Function `borrow_string`](#0x1_type_name_borrow_string) -- [Function `get_address`](#0x1_type_name_get_address) -- [Function `get_module`](#0x1_type_name_get_module) -- [Function `into_string`](#0x1_type_name_into_string) - - -

-use 0x1::address;
-use 0x1::ascii;
-
- - - - - -## Struct `TypeName` - - - -

-struct TypeName has copy, drop, store
-
- - - -
-Fields - - -
-
- -name: ascii::String -
-
- String representation of the type. All types are represented - using their source syntax: - "u8", "u64", "bool", "address", "vector", and so on for primitive types. - Struct types are represented as fully qualified type names; e.g. - -00000000000000000000000000000001::string::String or - -0000000000000000000000000000000a::module_name1::type_name1<0000000000000000000000000000000a::module_name2::type_name2<u64>> - Addresses are hex-encoded lowercase values of length ADDRESS_LENGTH (16, 20, or 32 depending on the Move platform) -
-
- - -
- - - -## Constants - - - - -ASCII Character code for the -c (lowercase c) symbol. - - -

-const ASCII_C: u8 = 99;
-
- - - - - -ASCII Character code for the -: (colon) symbol. - - -

-const ASCII_COLON: u8 = 58;
-
- - - - - -ASCII Character code for the -e (lowercase e) symbol. - - -

-const ASCII_E: u8 = 101;
-
- - - - - -ASCII Character code for the -o (lowercase o) symbol. - - -

-const ASCII_O: u8 = 111;
-
- - - - - -ASCII Character code for the -r (lowercase r) symbol. - - -

-const ASCII_R: u8 = 114;
-
- - - - - -ASCII Character code for the -t (lowercase t) symbol. - - -

-const ASCII_T: u8 = 116;
-
- - - - - -ASCII Character code for the -v (lowercase v) symbol. - - -

-const ASCII_V: u8 = 118;
-
- - - - - -The type is not from a package/module. It is a primitive type. - - -

-const ENonModuleType: u64 = 0;
-
- - - - - -## Function `get` - -Return a value representation of the type -T. Package IDs -that appear in fully qualified type names in the output from -this function are defining IDs (the ID of the package in -storage that first introduced the type). - - -

-public fun get<T>(): type_name::TypeName
-
- - - -
-Implementation - - -

-public native fun get<T>(): TypeName;
-
- - - -
- - - -## Function `get_with_original_ids` - -Return a value representation of the type -T. Package IDs -that appear in fully qualified type names in the output from -this function are original IDs (the ID of the first version of -the package, even if the type in question was introduced in a -later upgrade). - - -

-public fun get_with_original_ids<T>(): type_name::TypeName
-
- - - -
-Implementation - - -

-public native fun get_with_original_ids<T>(): TypeName;
-
- - - -
- - - -## Function `is_primitive` - -Returns true iff the TypeName represents a primitive type, i.e. one of -u8, u16, u32, u64, u128, u256, bool, address, vector. - - -

-public fun is_primitive(self: &type_name::TypeName): bool
-
- - - -
-Implementation - - -

-public fun is_primitive(self: &TypeName): bool \{
-    let bytes = self.name.as_bytes();
-    bytes == &b"bool" ||
-    bytes == &b"u8" ||
-    bytes == &b"u16" ||
-    bytes == &b"u32" ||
-    bytes == &b"u64" ||
-    bytes == &b"u128" ||
-    bytes == &b"u256" ||
-    bytes == &b"address" ||
-    (bytes.length() >= 6 &&
-     bytes[0] == ASCII_V &&
-     bytes[1] == ASCII_E &&
-     bytes[2] == ASCII_C &&
-     bytes[3] == ASCII_T &&
-     bytes[4] == ASCII_O &&
-     bytes[5] == ASCII_R)
-
-}
-
- - - -
- - - -## Function `borrow_string` - -Get the String representation of -self - - -

-public fun borrow_string(self: &type_name::TypeName): &ascii::String
-
- - - -
-Implementation - - -

-public fun borrow_string(self: &TypeName): &String \{
-    &self.name
-}
-
- - - -
- - - -## Function `get_address` - -Get Address string (Base16 encoded), first part of the TypeName. -Aborts if given a primitive type. - - -

-public fun get_address(self: &type_name::TypeName): ascii::String
-
- - - -
-Implementation - - -

-public fun get_address(self: &TypeName): String \{
-    assert!(!self.is_primitive(), ENonModuleType);
-
-    // Base16 (string) representation of an address has 2 symbols per byte.
-    let len = address::length() * 2;
-    let str_bytes = self.name.as_bytes();
-    let mut addr_bytes = vector[];
-    let mut i = 0;
-
-    // Read `len` bytes from the type name and push them to addr_bytes.
-    while (i < len) \{
-        addr_bytes.push_back(str_bytes[i]);
-        i = i + 1;
-    };
-
-    ascii::string(addr_bytes)
-}
-
- - - -
- - - -## Function `get_module` - -Get name of the module. -Aborts if given a primitive type. - - -

-public fun get_module(self: &type_name::TypeName): ascii::String
-
- - - -
-Implementation - - -

-public fun get_module(self: &TypeName): String \{
-    assert!(!self.is_primitive(), ENonModuleType);
-
-    // Starts after address and a double colon: `<addr as HEX>::`
-    let mut i = address::length() * 2 + 2;
-    let str_bytes = self.name.as_bytes();
-    let mut module_name = vector[];
-
-    loop \{
-        let char = &str_bytes[i];
-        if (char != &ASCII_COLON) \{
-            module_name.push_back(*char);
-            i = i + 1;
-        } else \{
-            break
-        }
-    };
-
-    ascii::string(module_name)
-}
-
- - - -
- - - -## Function `into_string` - -Convert -self into its inner String - - -

-public fun into_string(self: type_name::TypeName): ascii::String
-
- - - -
-Implementation - - -

-public fun into_string(self: TypeName): String \{
-    self.name
-}
-
- - - -
diff --git a/crates/iota-framework/docs/move-stdlib/vector.mdx b/crates/iota-framework/docs/move-stdlib/vector.mdx deleted file mode 100644 index 2733b95aab0..00000000000 --- a/crates/iota-framework/docs/move-stdlib/vector.mdx +++ /dev/null @@ -1,595 +0,0 @@ ---- -title: Module `0x1::vector` ---- -import Link from '@docusaurus/Link'; - - -A variable-sized container that can hold any type. Indexing is 0-based, and -vectors are growable. This module has many native functions. - - -- [Constants](#@Constants_0) -- [Function `empty`](#0x1_vector_empty) -- [Function `length`](#0x1_vector_length) -- [Function `borrow`](#0x1_vector_borrow) -- [Function `push_back`](#0x1_vector_push_back) -- [Function `borrow_mut`](#0x1_vector_borrow_mut) -- [Function `pop_back`](#0x1_vector_pop_back) -- [Function `destroy_empty`](#0x1_vector_destroy_empty) -- [Function `swap`](#0x1_vector_swap) -- [Function `singleton`](#0x1_vector_singleton) -- [Function `reverse`](#0x1_vector_reverse) -- [Function `append`](#0x1_vector_append) -- [Function `is_empty`](#0x1_vector_is_empty) -- [Function `contains`](#0x1_vector_contains) -- [Function `index_of`](#0x1_vector_index_of) -- [Function `remove`](#0x1_vector_remove) -- [Function `insert`](#0x1_vector_insert) -- [Function `swap_remove`](#0x1_vector_swap_remove) - - -

-
- - - - - -## Constants - - - - -The index into the vector is out of bounds - - -

-const EINDEX_OUT_OF_BOUNDS: u64 = 131072;
-
- - - - - -## Function `empty` - -Create an empty vector. - - -

-public fun empty<Element>(): vector<Element>
-
- - - -
-Implementation - - -

-native public fun empty<Element>(): vector<Element>;
-
- - - -
- - - -## Function `length` - -Return the length of the vector. - - -

-public fun length<Element>(v: &vector<Element>): u64
-
- - - -
-Implementation - - -

-native public fun length<Element>(v: &vector<Element>): u64;
-
- - - -
- - - -## Function `borrow` - -Acquire an immutable reference to the -ith element of the vector -v. -Aborts if -i is out of bounds. - - -

-public fun borrow<Element>(v: &vector<Element>, i: u64): &Element
-
- - - -
-Implementation - - -

-native public fun borrow<Element>(v: &vector<Element>, i: u64): ∈
-
- - - -
- - - -## Function `push_back` - -Add element -e to the end of the vector -v. - - -

-public fun push_back<Element>(v: &mut vector<Element>, e: Element)
-
- - - -
-Implementation - - -

-native public fun push_back<Element>(v: &mut vector<Element>, e: Element);
-
- - - -
- - - -## Function `borrow_mut` - -Return a mutable reference to the -ith element in the vector -v. -Aborts if -i is out of bounds. - - -

-public fun borrow_mut<Element>(v: &mut vector<Element>, i: u64): &mut Element
-
- - - -
-Implementation - - -

-native public fun borrow_mut<Element>(v: &mut vector<Element>, i: u64): &mut Element;
-
- - - -
- - - -## Function `pop_back` - -Pop an element from the end of vector -v. -Aborts if -v is empty. - - -

-public fun pop_back<Element>(v: &mut vector<Element>): Element
-
- - - -
-Implementation - - -

-native public fun pop_back<Element>(v: &mut vector<Element>): Element;
-
- - - -
- - - -## Function `destroy_empty` - -Destroy the vector -v. -Aborts if -v is not empty. - - -

-public fun destroy_empty<Element>(v: vector<Element>)
-
- - - -
-Implementation - - -

-native public fun destroy_empty<Element>(v: vector<Element>);
-
- - - -
- - - -## Function `swap` - -Swaps the elements at the -ith and -jth indices in the vector -v. -Aborts if -i or -j is out of bounds. - - -

-public fun swap<Element>(v: &mut vector<Element>, i: u64, j: u64)
-
- - - -
-Implementation - - -

-native public fun swap<Element>(v: &mut vector<Element>, i: u64, j: u64);
-
- - - -
- - - -## Function `singleton` - -Return an vector of size one containing element -e. - - -

-public fun singleton<Element>(e: Element): vector<Element>
-
- - - -
-Implementation - - -

-public fun singleton<Element>(e: Element): vector<Element> \{
-    let mut v = empty();
-    v.push_back(e);
-    v
-}
-
- - - -
- - - -## Function `reverse` - -Reverses the order of the elements in the vector -v in place. - - -

-public fun reverse<Element>(v: &mut vector<Element>)
-
- - - -
-Implementation - - -

-public fun reverse<Element>(v: &mut vector<Element>) \{
-    let len = v.length();
-    if (len == 0) return ();
-
-    let mut front_index = 0;
-    let mut back_index = len -1;
-    while (front_index < back_index) \{
-        v.swap(front_index, back_index);
-        front_index = front_index + 1;
-        back_index = back_index - 1;
-    }
-}
-
- - - -
- - - -## Function `append` - -Pushes all of the elements of the -other vector into the -lhs vector. - - -

-public fun append<Element>(lhs: &mut vector<Element>, other: vector<Element>)
-
- - - -
-Implementation - - -

-public fun append<Element>(lhs: &mut vector<Element>, mut other: vector<Element>) \{
-    other.reverse();
-    while (!other.is_empty()) lhs.push_back(other.pop_back());
-    other.destroy_empty();
-}
-
- - - -
- - - -## Function `is_empty` - -Return -true if the vector -v has no elements and -false otherwise. - - -

-public fun is_empty<Element>(v: &vector<Element>): bool
-
- - - -
-Implementation - - -

-public fun is_empty<Element>(v: &vector<Element>): bool \{
-    v.length() == 0
-}
-
- - - -
- - - -## Function `contains` - -Return true if -e is in the vector -v. -Otherwise, returns false. - - -

-public fun contains<Element>(v: &vector<Element>, e: &Element): bool
-
- - - -
-Implementation - - -

-public fun contains<Element>(v: &vector<Element>, e: &Element): bool \{
-    let mut i = 0;
-    let len = v.length();
-    while (i < len) \{
-        if (&v[i] == e) return true;
-        i = i + 1;
-    };
-    false
-}
-
- - - -
- - - -## Function `index_of` - -Return -(true, i) if -e is in the vector -v at index -i. -Otherwise, returns -(false, 0). - - -

-public fun index_of<Element>(v: &vector<Element>, e: &Element): (bool, u64)
-
- - - -
-Implementation - - -

-public fun index_of<Element>(v: &vector<Element>, e: &Element): (bool, u64) \{
-    let mut i = 0;
-    let len = v.length();
-    while (i < len) \{
-        if (&v[i] == e) return (true, i);
-        i = i + 1;
-    };
-    (false, 0)
-}
-
- - - -
- - - -## Function `remove` - -Remove the -ith element of the vector -v, shifting all subsequent elements. -This is O(n) and preserves ordering of elements in the vector. -Aborts if -i is out of bounds. - - -

-public fun remove<Element>(v: &mut vector<Element>, i: u64): Element
-
- - - -
-Implementation - - -

-public fun remove<Element>(v: &mut vector<Element>, mut i: u64): Element \{
-    let mut len = v.length();
-    // i out of bounds; abort
-    if (i >= len) abort EINDEX_OUT_OF_BOUNDS;
-
-    len = len - 1;
-    while (i < len) v.swap(i, \{ i = i + 1; i });
-    v.pop_back()
-}
-
- - - -
- - - -## Function `insert` - -Insert -e at position -i in the vector -v. -If -i is in bounds, this shifts the old -v[i] and all subsequent elements to the right. -If -i == v.length(), this adds -e to the end of the vector. -This is O(n) and preserves ordering of elements in the vector. -Aborts if -i > v.length() - - -

-public fun insert<Element>(v: &mut vector<Element>, e: Element, i: u64)
-
- - - -
-Implementation - - -

-public fun insert<Element>(v: &mut vector<Element>, e: Element, mut i: u64) \{
-    let len = v.length();
-    // i too big abort
-    if (i > len) abort EINDEX_OUT_OF_BOUNDS;
-
-    v.push_back(e);
-    while (i < len) \{
-        v.swap(i, len);
-        i = i + 1
-    }
-}
-
- - - -
- - - -## Function `swap_remove` - -Swap the -ith element of the vector -v with the last element and then pop the vector. -This is O(1), but does not preserve ordering of elements in the vector. -Aborts if -i is out of bounds. - - -

-public fun swap_remove<Element>(v: &mut vector<Element>, i: u64): Element
-
- - - -
-Implementation - - -

-public fun swap_remove<Element>(v: &mut vector<Element>, i: u64): Element \{
-    assert!(!v.is_empty(), EINDEX_OUT_OF_BOUNDS);
-    let last_idx = v.length() - 1;
-    v.swap(i, last_idx);
-    v.pop_back()
-}
-
- - - -
diff --git a/crates/iota-framework/docs/stardust/address_unlock_condition.mdx b/crates/iota-framework/docs/stardust/address_unlock_condition.mdx deleted file mode 100644 index f4b0474a8c1..00000000000 --- a/crates/iota-framework/docs/stardust/address_unlock_condition.mdx +++ /dev/null @@ -1,249 +0,0 @@ ---- -title: Module `0x107a::address_unlock_condition` ---- -import Link from '@docusaurus/Link'; - - - - -- [Function `unlock_alias_address_owned_basic`](#0x107a_address_unlock_condition_unlock_alias_address_owned_basic) -- [Function `unlock_alias_address_owned_nft`](#0x107a_address_unlock_condition_unlock_alias_address_owned_nft) -- [Function `unlock_alias_address_owned_alias`](#0x107a_address_unlock_condition_unlock_alias_address_owned_alias) -- [Function `unlock_alias_address_owned_coinmanager_treasury`](#0x107a_address_unlock_condition_unlock_alias_address_owned_coinmanager_treasury) -- [Function `unlock_nft_address_owned_basic`](#0x107a_address_unlock_condition_unlock_nft_address_owned_basic) -- [Function `unlock_nft_address_owned_nft`](#0x107a_address_unlock_condition_unlock_nft_address_owned_nft) -- [Function `unlock_nft_address_owned_alias`](#0x107a_address_unlock_condition_unlock_nft_address_owned_alias) - - -

-use 0x107a::alias;
-use 0x107a::alias_output;
-use 0x107a::basic_output;
-use 0x107a::nft;
-use 0x107a::nft_output;
-use 0x2::coin_manager;
-use 0x2::object;
-use 0x2::transfer;
-
- - - - - -## Function `unlock_alias_address_owned_basic` - -Unlock a -BasicOutput locked to the alias address. - - -

-public fun unlock_alias_address_owned_basic<T>(self: &mut alias::Alias, output_to_unlock: transfer::Receiving<basic_output::BasicOutput<T>>): basic_output::BasicOutput<T>
-
- - - -
-Implementation - - -

-public fun unlock_alias_address_owned_basic<T>(
-  self: &mut Alias,
-  output_to_unlock: Receiving<BasicOutput<T>>
-): BasicOutput<T> \{
-    basic_output::receive(self.id(), output_to_unlock)
-}
-
- - - -
- - - -## Function `unlock_alias_address_owned_nft` - -Unlock an -NftOutput locked to the alias address. - - -

-public fun unlock_alias_address_owned_nft<T>(self: &mut alias::Alias, output_to_unlock: transfer::Receiving<nft_output::NftOutput<T>>): nft_output::NftOutput<T>
-
- - - -
-Implementation - - -

-public fun unlock_alias_address_owned_nft<T>(
-  self: &mut Alias,
-  output_to_unlock: Receiving<NftOutput<T>>,
-): NftOutput<T> \{
-    nft_output::receive(self.id(), output_to_unlock)
-}
-
- - - -
- - - -## Function `unlock_alias_address_owned_alias` - -Unlock an -AliasOutput locked to the alias address. - - -

-public fun unlock_alias_address_owned_alias<T>(self: &mut alias::Alias, output_to_unlock: transfer::Receiving<alias_output::AliasOutput<T>>): alias_output::AliasOutput<T>
-
- - - -
-Implementation - - -

-public fun unlock_alias_address_owned_alias<T>(
-  self: &mut Alias,
-  output_to_unlock: Receiving<AliasOutput<T>>,
-): AliasOutput<T> \{
-    alias_output::receive(self.id(), output_to_unlock)
-}
-
- - - -
- - - -## Function `unlock_alias_address_owned_coinmanager_treasury` - -Unlock a -CoinManagerTreasuryCap locked to the alias address. - - -

-public fun unlock_alias_address_owned_coinmanager_treasury<T>(self: &mut alias::Alias, treasury_to_unlock: transfer::Receiving<coin_manager::CoinManagerTreasuryCap<T>>): coin_manager::CoinManagerTreasuryCap<T>
-
- - - -
-Implementation - - -

-public fun unlock_alias_address_owned_coinmanager_treasury<T>(
-  self: &mut Alias,
-  treasury_to_unlock: Receiving<CoinManagerTreasuryCap<T>>,
-): CoinManagerTreasuryCap<T> \{
-    transfer::public_receive(self.id(), treasury_to_unlock)
-}
-
- - - -
- - - -## Function `unlock_nft_address_owned_basic` - -Unlock a -BasicOutput locked to the -Nft address. - - -

-public fun unlock_nft_address_owned_basic<T>(self: &mut nft::Nft, output_to_unlock: transfer::Receiving<basic_output::BasicOutput<T>>): basic_output::BasicOutput<T>
-
- - - -
-Implementation - - -

-public fun unlock_nft_address_owned_basic<T>(
-  self: &mut Nft,
-  output_to_unlock: Receiving<BasicOutput<T>>,
-): BasicOutput<T> \{
-    basic_output::receive(self.id(), output_to_unlock)
-}
-
- - - -
- - - -## Function `unlock_nft_address_owned_nft` - -Unlock an -NftOutput locked to the -Nft address. - - -

-public fun unlock_nft_address_owned_nft<T>(self: &mut nft::Nft, output_to_unlock: transfer::Receiving<nft_output::NftOutput<T>>): nft_output::NftOutput<T>
-
- - - -
-Implementation - - -

-public fun unlock_nft_address_owned_nft<T>(
-  self: &mut Nft,
-  output_to_unlock: Receiving<NftOutput<T>>,
-): NftOutput<T> \{
-    nft_output::receive(self.id(), output_to_unlock)
-}
-
- - - -
- - - -## Function `unlock_nft_address_owned_alias` - -Unlock an -AliasOutput locked to the -Nft address. - - -

-public fun unlock_nft_address_owned_alias<T>(self: &mut nft::Nft, output_to_unlock: transfer::Receiving<alias_output::AliasOutput<T>>): alias_output::AliasOutput<T>
-
- - - -
-Implementation - - -

-public fun unlock_nft_address_owned_alias<T>(
-  self: &mut Nft,
-  output_to_unlock: Receiving<AliasOutput<T>>,
-): AliasOutput<T> \{
-    alias_output::receive(self.id(), output_to_unlock)
-}
-
- - - -
diff --git a/crates/iota-framework/docs/stardust/alias.mdx b/crates/iota-framework/docs/stardust/alias.mdx deleted file mode 100644 index e731433c3a0..00000000000 --- a/crates/iota-framework/docs/stardust/alias.mdx +++ /dev/null @@ -1,372 +0,0 @@ ---- -title: Module `0x107a::alias` ---- -import Link from '@docusaurus/Link'; - - - - -- [Resource `Alias`](#0x107a_alias_Alias) -- [Function `destroy`](#0x107a_alias_destroy) -- [Function `legacy_state_controller`](#0x107a_alias_legacy_state_controller) -- [Function `state_index`](#0x107a_alias_state_index) -- [Function `state_metadata`](#0x107a_alias_state_metadata) -- [Function `sender`](#0x107a_alias_sender) -- [Function `metadata`](#0x107a_alias_metadata) -- [Function `immutable_issuer`](#0x107a_alias_immutable_issuer) -- [Function `immutable_metadata`](#0x107a_alias_immutable_metadata) -- [Function `id`](#0x107a_alias_id) - - -

-use 0x1::option;
-use 0x2::object;
-
- - - - - -## Resource `Alias` - -The persisted Alias object from Stardust, without tokens and assets. -Outputs owned the AliasID/Address in Stardust will be sent to this object and -have to be received via this object once extracted from -AliasOutput. - - -

-struct Alias has store, key
-
- - - -
-Fields - - -
-
- -id: object::UID -
-
- The ID of the Alias = hash of the Output ID that created the Alias Output in Stardust. - This is the AliasID from Stardust. -
-
- -legacy_state_controller: address -
-
- The last State Controller address assigned before the migration. -
-
- -state_index: u32 -
-
- A counter increased by 1 every time the alias was state transitioned. -
-
- -state_metadata: option::Option<vector<u8>> -
-
- State metadata that can be used to store additional information. -
-
- -sender: option::Option<address> -
-
- The sender feature. -
-
- -metadata: option::Option<vector<u8>> -
-
- The metadata feature. -
-
- -immutable_issuer: option::Option<address> -
-
- The immutable issuer feature. -
-
- -immutable_metadata: option::Option<vector<u8>> -
-
- The immutable metadata feature. -
-
- - -
- - - -## Function `destroy` - -Destroy the -Alias object, equivalent to -burning an Alias Output in Stardust. - - -

-public fun destroy(self: alias::Alias)
-
- - - -
-Implementation - - -

-public fun destroy(self: Alias) \{
-    let Alias \{
-        id,
-        legacy_state_controller: _,
-        state_index: _,
-        state_metadata: _,
-        sender: _,
-        metadata: _,
-        immutable_issuer: _,
-        immutable_metadata: _,
-    } = self;
-
-    object::delete(id);
-}
-
- - - -
- - - -## Function `legacy_state_controller` - -Get the Alias's -legacy_state_controller. - - -

-public fun legacy_state_controller(self: &alias::Alias): &address
-
- - - -
-Implementation - - -

-public fun legacy_state_controller(self: &Alias): &address \{
-    &self.legacy_state_controller
-}
-
- - - -
- - - -## Function `state_index` - -Get the Alias's -state_index. - - -

-public fun state_index(self: &alias::Alias): u32
-
- - - -
-Implementation - - -

-public fun state_index(self: &Alias): u32 \{
-    self.state_index
-}
-
- - - -
- - - -## Function `state_metadata` - -Get the Alias's -state_metadata. - - -

-public fun state_metadata(self: &alias::Alias): &option::Option<vector<u8>>
-
- - - -
-Implementation - - -

-public fun state_metadata(self: &Alias): &Option<vector<u8>> \{
-    &self.state_metadata
-}
-
- - - -
- - - -## Function `sender` - -Get the Alias's -sender. - - -

-public fun sender(self: &alias::Alias): &option::Option<address>
-
- - - -
-Implementation - - -

-public fun sender(self: &Alias): &Option<address> \{
-    &self.sender
-}
-
- - - -
- - - -## Function `metadata` - -Get the Alias's -metadata. - - -

-public fun metadata(self: &alias::Alias): &option::Option<vector<u8>>
-
- - - -
-Implementation - - -

-public fun metadata(self: &Alias): &Option<vector<u8>> \{
-    &self.metadata
-}
-
- - - -
- - - -## Function `immutable_issuer` - -Get the Alias's -immutable_sender. - - -

-public fun immutable_issuer(self: &alias::Alias): &option::Option<address>
-
- - - -
-Implementation - - -

-public fun immutable_issuer(self: &Alias): &Option<address> \{
-    &self.immutable_issuer
-}
-
- - - -
- - - -## Function `immutable_metadata` - -Get the Alias's -immutable_metadata. - - -

-public fun immutable_metadata(self: &alias::Alias): &option::Option<vector<u8>>
-
- - - -
-Implementation - - -

-public fun immutable_metadata(self: &Alias): &Option<vector<u8>> \{
-    &self.immutable_metadata
-}
-
- - - -
- - - -## Function `id` - -Get the Alias's id. - - -

-public(friend) fun id(self: &mut alias::Alias): &mut object::UID
-
- - - -
-Implementation - - -

-public(package) fun id(self: &mut Alias): &mut UID \{
-    &mut self.id
-}
-
- - - -
diff --git a/crates/iota-framework/docs/stardust/alias_output.mdx b/crates/iota-framework/docs/stardust/alias_output.mdx deleted file mode 100644 index d783043e09d..00000000000 --- a/crates/iota-framework/docs/stardust/alias_output.mdx +++ /dev/null @@ -1,220 +0,0 @@ ---- -title: Module `0x107a::alias_output` ---- -import Link from '@docusaurus/Link'; - - - - -- [Resource `AliasOutput`](#0x107a_alias_output_AliasOutput) -- [Constants](#@Constants_0) -- [Function `extract_assets`](#0x107a_alias_output_extract_assets) -- [Function `receive`](#0x107a_alias_output_receive) -- [Function `attach_alias`](#0x107a_alias_output_attach_alias) -- [Function `load_alias`](#0x107a_alias_output_load_alias) - - -

-use 0x107a::alias;
-use 0x2::bag;
-use 0x2::balance;
-use 0x2::dynamic_object_field;
-use 0x2::object;
-use 0x2::transfer;
-
- - - - - -## Resource `AliasOutput` - -Owned Object controlled by the Governor Address. - - -

-struct AliasOutput<T> has key
-
- - - -
-Fields - - -
-
- -id: object::UID -
-
- This is a "random" UID, not the AliasID from Stardust. -
-
- -balance: balance::Balance<T> -
-
- The amount of coins held by the output. -
-
- -native_tokens: bag::Bag -
-
- The -Bag holds native tokens, key-ed by the stringified type of the asset. - Example: key: "0xabcded::soon::SOON", value: `Balance<0xabcded::soon::SOON>`. -
-
- - -
- - - -## Constants - - - - -The Alias dynamic object field name. - - -

-const ALIAS_NAME: vector<u8> = [97, 108, 105, 97, 115];
-
- - - - - -## Function `extract_assets` - -The function extracts assets from a legacy -AliasOutput. -- returns the coin Balance, -- the native tokens Bag, -- and the -Alias object that persists the AliasID=ObjectID from Stardust. - - -

-public fun extract_assets<T>(output: alias_output::AliasOutput<T>): (balance::Balance<T>, bag::Bag, alias::Alias)
-
- - - -
-Implementation - - -

-public fun extract_assets<T>(mut output: AliasOutput<T>): (Balance<T>, Bag, Alias) \{
-    // Load the related alias object.
-    let alias = load_alias(&mut output);
-
-    // Unpack the output into its basic part.
-    let AliasOutput \{
-        id,
-        balance,
-        native_tokens
-    } = output;
-
-    // Delete the output.
-    object::delete(id);
-
-    (balance, native_tokens, alias)
-}
-
- - - -
- - - -## Function `receive` - -Utility function to receive an -AliasOutput object in other Stardust modules. -Other modules in the Stardust package can call this function to receive an -AliasOutput object (nft). - - -

-public(friend) fun receive<T>(parent: &mut object::UID, output: transfer::Receiving<alias_output::AliasOutput<T>>): alias_output::AliasOutput<T>
-
- - - -
-Implementation - - -

-public(package) fun receive<T>(parent: &mut UID, output: Receiving<AliasOutput<T>>) : AliasOutput<T> \{
-    transfer::receive(parent, output)
-}
-
- - - -
- - - -## Function `attach_alias` - -Utility function to attach an -Alias to an -AliasOutput. - - -

-public fun attach_alias<T>(output: &mut alias_output::AliasOutput<T>, alias: alias::Alias)
-
- - - -
-Implementation - - -

-public fun attach_alias<T>(output: &mut AliasOutput<T>, alias: Alias) \{
-    dynamic_object_field::add(&mut output.id, ALIAS_NAME, alias)
-}
-
- - - -
- - - -## Function `load_alias` - -Loads the -Alias object from the dynamic object field. - - -

-fun load_alias<T>(output: &mut alias_output::AliasOutput<T>): alias::Alias
-
- - - -
-Implementation - - -

-fun load_alias<T>(output: &mut AliasOutput<T>): Alias \{
-    dynamic_object_field::remove(&mut output.id, ALIAS_NAME)
-}
-
- - - -
diff --git a/crates/iota-framework/docs/stardust/basic_output.mdx b/crates/iota-framework/docs/stardust/basic_output.mdx deleted file mode 100644 index 6b9175bda16..00000000000 --- a/crates/iota-framework/docs/stardust/basic_output.mdx +++ /dev/null @@ -1,224 +0,0 @@ ---- -title: Module `0x107a::basic_output` ---- -import Link from '@docusaurus/Link'; - - - - -- [Resource `BasicOutput`](#0x107a_basic_output_BasicOutput) -- [Function `extract_assets`](#0x107a_basic_output_extract_assets) -- [Function `receive`](#0x107a_basic_output_receive) - - -

-use 0x107a::expiration_unlock_condition;
-use 0x107a::storage_deposit_return_unlock_condition;
-use 0x107a::timelock_unlock_condition;
-use 0x1::option;
-use 0x2::bag;
-use 0x2::balance;
-use 0x2::object;
-use 0x2::transfer;
-use 0x2::tx_context;
-
- - - - - -## Resource `BasicOutput` - -A basic output that has unlock conditions/features. -- basic outputs with expiration unlock condition must be a shared object, since that's the only -way to handle the two possible addresses that can unlock the output. -- notice that there is no -store ability and there is no custom transfer function: -- you can call -extract_assets, -- or you can call -receive in other models to receive a -BasicOutput. - - -

-struct BasicOutput<T> has key
-
- - - -
-Fields - - -
-
- -id: object::UID -
-
- Hash of the -outputId that was migrated. -
-
- -balance: balance::Balance<T> -
-
- The amount of coins held by the output. -
-
- -native_tokens: bag::Bag -
-
- The -Bag holds native tokens, key-ed by the stringified type of the asset. - Example: key: "0xabcded::soon::SOON", value: `Balance<0xabcded::soon::SOON>`. -
-
- -storage_deposit_return_uc: option::Option<storage_deposit_return_unlock_condition::StorageDepositReturnUnlockCondition> -
-
- The storage deposit return unlock condition. -
-
- -timelock_uc: option::Option<timelock_unlock_condition::TimelockUnlockCondition> -
-
- The timelock unlock condition. -
-
- -expiration_uc: option::Option<expiration_unlock_condition::ExpirationUnlockCondition> -
-
- The expiration unlock condition. -
-
- -metadata: option::Option<vector<u8>> -
-
- The metadata feature. -
-
- -tag: option::Option<vector<u8>> -
-
- The tag feature. -
-
- -sender: option::Option<address> -
-
- The sender feature. -
-
- - -
- - - -## Function `extract_assets` - -Extract the assets stored inside the output, respecting the unlock conditions. -- The object will be deleted. -- The -StorageDepositReturnUnlockCondition will return the deposit. -- Remaining assets (coins and native tokens) will be returned. - - -

-public fun extract_assets<T>(output: basic_output::BasicOutput<T>, ctx: &mut tx_context::TxContext): (balance::Balance<T>, bag::Bag)
-
- - - -
-Implementation - - -

-public fun extract_assets<T>(output: BasicOutput<T>, ctx: &mut TxContext) : (Balance<T>, Bag) \{
-    // Unpack the output into its basic part.
-    let BasicOutput \{
-        id,
-        balance: mut balance,
-        native_tokens,
-        storage_deposit_return_uc: mut storage_deposit_return_uc,
-        timelock_uc: mut timelock_uc,
-        expiration_uc: mut expiration_uc,
-        sender: _,
-        metadata: _,
-        tag: _
-    } = output;
-
-    // If the output has a timelock unlock condition, then we need to check if the timelock_uc has expired.
-    if (timelock_uc.is_some()) \{
-        timelock_uc.extract().unlock(ctx);
-    };
-
-    // If the output has an expiration unlock condition, then we need to check who can unlock the output.
-    if (expiration_uc.is_some()) \{
-        expiration_uc.extract().unlock(ctx);
-    };
-
-    // If the output has an storage deposit return unlock condition, then we need to return the deposit.
-    if (storage_deposit_return_uc.is_some()) \{
-        storage_deposit_return_uc.extract().unlock(&mut balance, ctx);
-    };
-
-    // Destroy the unlock conditions.
-    option::destroy_none(timelock_uc);
-    option::destroy_none(expiration_uc);
-    option::destroy_none(storage_deposit_return_uc);
-
-    // Delete the output.
-    object::delete(id);
-
-    return (balance, native_tokens)
-}
-
- - - -
- - - -## Function `receive` - -Utility function to receive a basic output in other stardust modules. -Since -BasicOutput only has -key, it can not be received via -public_receive. -The private receiver must be implemented in its defining module (here). -Other modules in the Stardust package can call this function to receive a basic output (alias, NFT). - - -

-public(friend) fun receive<T>(parent: &mut object::UID, output: transfer::Receiving<basic_output::BasicOutput<T>>): basic_output::BasicOutput<T>
-
- - - -
-Implementation - - -

-public(package) fun receive<T>(parent: &mut UID, output: Receiving<BasicOutput<T>>) : BasicOutput<T> \{
-    transfer::receive(parent, output)
-}
-
- - - -
diff --git a/crates/iota-framework/docs/stardust/expiration_unlock_condition.mdx b/crates/iota-framework/docs/stardust/expiration_unlock_condition.mdx deleted file mode 100644 index 653f19cdcc5..00000000000 --- a/crates/iota-framework/docs/stardust/expiration_unlock_condition.mdx +++ /dev/null @@ -1,235 +0,0 @@ ---- -title: Module `0x107a::expiration_unlock_condition` ---- -import Link from '@docusaurus/Link'; - - - - -- [Struct `ExpirationUnlockCondition`](#0x107a_expiration_unlock_condition_ExpirationUnlockCondition) -- [Constants](#@Constants_0) -- [Function `unlock`](#0x107a_expiration_unlock_condition_unlock) -- [Function `can_be_unlocked_by`](#0x107a_expiration_unlock_condition_can_be_unlocked_by) -- [Function `owner`](#0x107a_expiration_unlock_condition_owner) -- [Function `return_address`](#0x107a_expiration_unlock_condition_return_address) -- [Function `unix_time`](#0x107a_expiration_unlock_condition_unix_time) - - -

-use 0x2::tx_context;
-
- - - - - -## Struct `ExpirationUnlockCondition` - -The Stardust expiration unlock condition. - - -

-struct ExpirationUnlockCondition has store
-
- - - -
-Fields - - -
-
- -owner: address -
-
- The address who owns the output before the timestamp has passed. -
-
- -return_address: address -
-
- The address that is allowed to spend the locked funds after the timestamp has passed. -
-
- -unix_time: u32 -
-
- Before this unix time, Address Unlock Condition is allowed to unlock the output, after that only the address defined in Return Address. -
-
- - -
- - - -## Constants - - - - -The output can not be unlocked by the sender error. - - -

-const EWrongSender: u64 = 0;
-
- - - - - -## Function `unlock` - -Check the unlock condition. - - -

-public fun unlock(condition: expiration_unlock_condition::ExpirationUnlockCondition, ctx: &mut tx_context::TxContext)
-
- - - -
-Implementation - - -

-public fun unlock(condition: ExpirationUnlockCondition, ctx: &mut TxContext) \{
-    let unlock_address = condition.can_be_unlocked_by(ctx);
-
-    assert!(unlock_address == ctx.sender(), EWrongSender);
-
-    let ExpirationUnlockCondition \{
-        owner: _,
-        return_address: _,
-        unix_time: _,
-    } = condition;
-}
-
- - - -
- - - -## Function `can_be_unlocked_by` - -Return the address that can unlock the related output. - - -

-public fun can_be_unlocked_by(condition: &expiration_unlock_condition::ExpirationUnlockCondition, ctx: &tx_context::TxContext): address
-
- - - -
-Implementation - - -

-public fun can_be_unlocked_by(condition: &ExpirationUnlockCondition, ctx: &TxContext): address \{
-    // Unix time in seconds.
-    let current_time = ((tx_context::epoch_timestamp_ms(ctx) / 1000) as u32);
-
-    if (condition.unix_time() <= current_time) \{
-        condition.return_address()
-    } else \{
-        condition.owner()
-    }
-}
-
- - - -
- - - -## Function `owner` - -Get the unlock condition's -owner. - - -

-public fun owner(condition: &expiration_unlock_condition::ExpirationUnlockCondition): address
-
- - - -
-Implementation - - -

-public fun owner(condition: &ExpirationUnlockCondition): address \{
-    condition.owner
-}
-
- - - -
- - - -## Function `return_address` - -Get the unlock condition's -return_address. - - -

-public fun return_address(condition: &expiration_unlock_condition::ExpirationUnlockCondition): address
-
- - - -
-Implementation - - -

-public fun return_address(condition: &ExpirationUnlockCondition): address \{
-    condition.return_address
-}
-
- - - -
- - - -## Function `unix_time` - -Get the unlock condition's -unix_time. - - -

-public fun unix_time(condition: &expiration_unlock_condition::ExpirationUnlockCondition): u32
-
- - - -
-Implementation - - -

-public fun unix_time(condition: &ExpirationUnlockCondition): u32 \{
-    condition.unix_time
-}
-
- - - -
diff --git a/crates/iota-framework/docs/stardust/irc27.mdx b/crates/iota-framework/docs/stardust/irc27.mdx deleted file mode 100644 index a6b3d4ca40e..00000000000 --- a/crates/iota-framework/docs/stardust/irc27.mdx +++ /dev/null @@ -1,464 +0,0 @@ ---- -title: Module `0x107a::irc27` ---- -import Link from '@docusaurus/Link'; - - - - -- [Struct `Irc27Metadata`](#0x107a_irc27_Irc27Metadata) -- [Function `version`](#0x107a_irc27_version) -- [Function `media_type`](#0x107a_irc27_media_type) -- [Function `uri`](#0x107a_irc27_uri) -- [Function `name`](#0x107a_irc27_name) -- [Function `collection_name`](#0x107a_irc27_collection_name) -- [Function `royalties`](#0x107a_irc27_royalties) -- [Function `issuer_name`](#0x107a_irc27_issuer_name) -- [Function `description`](#0x107a_irc27_description) -- [Function `attributes`](#0x107a_irc27_attributes) -- [Function `non_standard_fields`](#0x107a_irc27_non_standard_fields) -- [Function `destroy`](#0x107a_irc27_destroy) - - -

-use 0x1::fixed_point32;
-use 0x1::option;
-use 0x1::string;
-use 0x2::url;
-use 0x2::vec_map;
-
- - - - - -## Struct `Irc27Metadata` - -The IRC27 NFT metadata standard schema. - - -

-struct Irc27Metadata has store
-
- - - -
-Fields - - -
-
- -version: string::String -
-
- Version of the metadata standard. -
-
- -media_type: string::String -
-
- The media type (MIME) of the asset. - - ## Examples - - Image files: -image/jpeg, -image/png, -image/gif, etc. - - Video files: -video/x-msvideo (avi), -video/mp4, -video/mpeg, etc. - - Audio files: -audio/mpeg, -audio/wav, etc. - - 3D Assets: -model/obj, -model/u3d, etc. - - Documents: -application/pdf, -text/plain, etc. -
-
- -uri: url::Url -
-
- URL pointing to the NFT file location. -
-
- -name: string::String -
-
- Alphanumeric text string defining the human identifiable name for the NFT. -
-
- -collection_name: option::Option<string::String> -
-
- The human-readable collection name of the NFT. -
-
- -royalties: vec_map::VecMap<address, fixed_point32::FixedPoint32> -
-
- Royalty payment addresses mapped to the payout percentage. - Contains a hash of the 32 bytes parsed from the BECH32 encoded IOTA address in the metadata, it is a legacy address. - Royalties are not supported by the protocol and needed to be processed by an integrator. -
-
- -issuer_name: option::Option<string::String> -
-
- The human-readable name of the NFT creator. -
-
- -description: option::Option<string::String> -
-
- The human-readable description of the NFT. -
-
- -attributes: vec_map::VecMap<string::String, string::String> -
-
- Additional attributes which follow [OpenSea Metadata standards](https://docs.opensea.io/docs/metadata-standards). -
-
- -non_standard_fields: vec_map::VecMap<string::String, string::String> -
-
- Legacy non-standard metadata fields. -
-
- - -
- - - -## Function `version` - -Get the metadata's -version. - - -

-public fun version(irc27: &irc27::Irc27Metadata): &string::String
-
- - - -
-Implementation - - -

-public fun version(irc27: &Irc27Metadata): &String \{
-    &irc27.version
-}
-
- - - -
- - - -## Function `media_type` - -Get the metadata's -media_type. - - -

-public fun media_type(irc27: &irc27::Irc27Metadata): &string::String
-
- - - -
-Implementation - - -

-public fun media_type(irc27: &Irc27Metadata): &String \{
-    &irc27.media_type
-}
-
- - - -
- - - -## Function `uri` - -Get the metadata's -uri. - - -

-public fun uri(irc27: &irc27::Irc27Metadata): &url::Url
-
- - - -
-Implementation - - -

-public fun uri(irc27: &Irc27Metadata): &Url \{
-    &irc27.uri
-}
-
- - - -
- - - -## Function `name` - -Get the metadata's -name. - - -

-public fun name(irc27: &irc27::Irc27Metadata): &string::String
-
- - - -
-Implementation - - -

-public fun name(irc27: &Irc27Metadata): &String \{
-    &irc27.name
-}
-
- - - -
- - - -## Function `collection_name` - -Get the metadata's -collection_name. - - -

-public fun collection_name(irc27: &irc27::Irc27Metadata): &option::Option<string::String>
-
- - - -
-Implementation - - -

-public fun collection_name(irc27: &Irc27Metadata): &Option<String> \{
-    &irc27.collection_name
-}
-
- - - -
- - - -## Function `royalties` - -Get the metadata's -royalties. - - -

-public fun royalties(irc27: &irc27::Irc27Metadata): &vec_map::VecMap<address, fixed_point32::FixedPoint32>
-
- - - -
-Implementation - - -

-public fun royalties(irc27: &Irc27Metadata): &VecMap<address, FixedPoint32> \{
-    &irc27.royalties
-}
-
- - - -
- - - -## Function `issuer_name` - -Get the metadata's -issuer_name. - - -

-public fun issuer_name(irc27: &irc27::Irc27Metadata): &option::Option<string::String>
-
- - - -
-Implementation - - -

-public fun issuer_name(irc27: &Irc27Metadata): &Option<String> \{
-    &irc27.issuer_name
-}
-
- - - -
- - - -## Function `description` - -Get the metadata's -description. - - -

-public fun description(irc27: &irc27::Irc27Metadata): &option::Option<string::String>
-
- - - -
-Implementation - - -

-public fun description(irc27: &Irc27Metadata): &Option<String> \{
-    &irc27.description
-}
-
- - - -
- - - -## Function `attributes` - -Get the metadata's -attributes. - - -

-public fun attributes(irc27: &irc27::Irc27Metadata): &vec_map::VecMap<string::String, string::String>
-
- - - -
-Implementation - - -

-public fun attributes(irc27: &Irc27Metadata): &VecMap<String, String> \{
-    &irc27.attributes
-}
-
- - - -
- - - -## Function `non_standard_fields` - -Get the metadata's -non_standard_fields. - - -

-public fun non_standard_fields(irc27: &irc27::Irc27Metadata): &vec_map::VecMap<string::String, string::String>
-
- - - -
-Implementation - - -

-public fun non_standard_fields(irc27: &Irc27Metadata): &VecMap<String, String> \{
-    &irc27.non_standard_fields
-}
-
- - - -
- - - -## Function `destroy` - -Permanently destroy a -Irc27Metadata object. - - -

-public fun destroy(irc27: irc27::Irc27Metadata)
-
- - - -
-Implementation - - -

-public fun destroy(irc27: Irc27Metadata) \{
-    let Irc27Metadata \{
-        version: _,
-        media_type: _,
-        uri: _,
-        name: _,
-        collection_name: _,
-        royalties: _,
-        issuer_name: _,
-        description: _,
-        attributes: _,
-        non_standard_fields: _,
-    } = irc27;
- }
-
- - - -
diff --git a/crates/iota-framework/docs/stardust/nft.mdx b/crates/iota-framework/docs/stardust/nft.mdx deleted file mode 100644 index e5001949746..00000000000 --- a/crates/iota-framework/docs/stardust/nft.mdx +++ /dev/null @@ -1,412 +0,0 @@ ---- -title: Module `0x107a::nft` ---- -import Link from '@docusaurus/Link'; - - - - -- [Struct `NFT`](#0x107a_nft_NFT) -- [Resource `Nft`](#0x107a_nft_Nft) -- [Function `init`](#0x107a_nft_init) -- [Function `destroy`](#0x107a_nft_destroy) -- [Function `legacy_sender`](#0x107a_nft_legacy_sender) -- [Function `metadata`](#0x107a_nft_metadata) -- [Function `tag`](#0x107a_nft_tag) -- [Function `immutable_issuer`](#0x107a_nft_immutable_issuer) -- [Function `immutable_metadata`](#0x107a_nft_immutable_metadata) -- [Function `id`](#0x107a_nft_id) - - -

-use 0x107a::irc27;
-use 0x1::option;
-use 0x1::string;
-use 0x2::display;
-use 0x2::object;
-use 0x2::package;
-use 0x2::transfer;
-use 0x2::tx_context;
-
- - - - - -## Struct `NFT` - -One Time Witness. - - -

-struct NFT has drop
-
- - - -
-Fields - - -
-
- -dummy_field: bool -
-
- -
-
- - -
- - - -## Resource `Nft` - -The Stardust NFT representation. - - -

-struct Nft has store, key
-
- - - -
-Fields - - -
-
- -id: object::UID -
-
- The Nft's ID is nested from Stardust. -
-
- -legacy_sender: option::Option<address> -
-
- The sender feature holds the last sender address assigned before the migration and - is not supported by the protocol after it. -
-
- -metadata: option::Option<vector<u8>> -
-
- The metadata feature. -
-
- -tag: option::Option<vector<u8>> -
-
- The tag feature. -
-
- -immutable_issuer: option::Option<address> -
-
- The immutable issuer feature. -
-
- -immutable_metadata: irc27::Irc27Metadata -
-
- The immutable metadata feature. -
-
- - -
- - - -## Function `init` - -The -Nft module initializer. - - -

-fun init(otw: nft::NFT, ctx: &mut tx_context::TxContext)
-
- - - -
-Implementation - - -

-fun init(otw: NFT, ctx: &mut TxContext) \{
-    // Claim the module publisher.
-    let publisher = package::claim(otw, ctx);
-
-    // Build a `Display` object.
-    let keys = vector[
-        // The Iota standard fields.
-        string::utf8(b"name"),
-        string::utf8(b"image_url"),
-        string::utf8(b"description"),
-        string::utf8(b"creator"),
-
-        // The extra IRC27-nested fields.
-        string::utf8(b"version"),
-        string::utf8(b"media_type"),
-        string::utf8(b"collection_name"),
-
-        // The issuer of the NFT. Equivalent to IRC-27 `collectionId`.
-        string::utf8(b"immutable_issuer"),
-    ];
-
-    let values = vector[
-        // The Iota standard fields.
-        string::utf8(b"\{immutable_metadata.name}"),
-        string::utf8(b"\{immutable_metadata.uri}"),
-        string::utf8(b"\{immutable_metadata.description}"),
-        string::utf8(b"\{immutable_metadata.issuer_name}"),
-
-        // The extra IRC27-nested fields.
-        string::utf8(b"\{immutable_metadata.version}"),
-        string::utf8(b"\{immutable_metadata.media_type}"),
-        string::utf8(b"\{immutable_metadata.collection_name}"),
-
-        // The issuer of the NFT. Equivalent to IRC-27 `collectionId`.
-        string::utf8(b"\{immutable_issuer}"),
-    ];
-
-    let mut display = display::new_with_fields<Nft>(
-        &publisher,
-        keys,
-        values,
-        ctx
-    );
-
-    // Commit the first version of `Display` to apply changes.
-    display.update_version();
-
-    // Burn the publisher object.
-    package::burn_publisher(publisher);
-
-    // Freeze the display object.
-    iota::transfer::public_freeze_object(display);
-}
-
- - - -
- - - -## Function `destroy` - -Permanently destroy an -Nft object. - - -

-public fun destroy(nft: nft::Nft)
-
- - - -
-Implementation - - -

-public fun destroy(nft: Nft) \{
-    let Nft \{
-        id,
-        legacy_sender: _,
-        metadata: _,
-        tag: _,
-        immutable_issuer: _,
-        immutable_metadata,
-    } = nft;
-
-    irc27::destroy(immutable_metadata);
-
-    object::delete(id);
-}
-
- - - -
- - - -## Function `legacy_sender` - -Get the Nft's -legacy_sender. - - -

-public fun legacy_sender(nft: &nft::Nft): &option::Option<address>
-
- - - -
-Implementation - - -

-public fun legacy_sender(nft: &Nft): &Option<address> \{
-    &nft.legacy_sender
-}
-
- - - -
- - - -## Function `metadata` - -Get the Nft's -metadata. - - -

-public fun metadata(nft: &nft::Nft): &option::Option<vector<u8>>
-
- - - -
-Implementation - - -

-public fun metadata(nft: &Nft): &Option<vector<u8>> \{
-    &nft.metadata
-}
-
- - - -
- - - -## Function `tag` - -Get the Nft's -tag. - - -

-public fun tag(nft: &nft::Nft): &option::Option<vector<u8>>
-
- - - -
-Implementation - - -

-public fun tag(nft: &Nft): &Option<vector<u8>> \{
-    &nft.tag
-}
-
- - - -
- - - -## Function `immutable_issuer` - -Get the Nft's -immutable_sender. - - -

-public fun immutable_issuer(nft: &nft::Nft): &option::Option<address>
-
- - - -
-Implementation - - -

-public fun immutable_issuer(nft: &Nft): &Option<address> \{
-    &nft.immutable_issuer
-}
-
- - - -
- - - -## Function `immutable_metadata` - -Get the Nft's -immutable_metadata. - - -

-public fun immutable_metadata(nft: &nft::Nft): &irc27::Irc27Metadata
-
- - - -
-Implementation - - -

-public fun immutable_metadata(nft: &Nft): &Irc27Metadata \{
-    &nft.immutable_metadata
-}
-
- - - -
- - - -## Function `id` - -Get the Nft's id. - - -

-public(friend) fun id(self: &mut nft::Nft): &mut object::UID
-
- - - -
-Implementation - - -

-public(package) fun id(self: &mut Nft): &mut UID \{
-    &mut self.id
-}
-
- - - -
diff --git a/crates/iota-framework/docs/stardust/nft_output.mdx b/crates/iota-framework/docs/stardust/nft_output.mdx deleted file mode 100644 index c66f69be58d..00000000000 --- a/crates/iota-framework/docs/stardust/nft_output.mdx +++ /dev/null @@ -1,263 +0,0 @@ ---- -title: Module `0x107a::nft_output` ---- -import Link from '@docusaurus/Link'; - - - - -- [Resource `NftOutput`](#0x107a_nft_output_NftOutput) -- [Constants](#@Constants_0) -- [Function `extract_assets`](#0x107a_nft_output_extract_assets) -- [Function `load_nft`](#0x107a_nft_output_load_nft) -- [Function `attach_nft`](#0x107a_nft_output_attach_nft) -- [Function `receive`](#0x107a_nft_output_receive) - - -

-use 0x107a::expiration_unlock_condition;
-use 0x107a::nft;
-use 0x107a::storage_deposit_return_unlock_condition;
-use 0x107a::timelock_unlock_condition;
-use 0x1::option;
-use 0x2::bag;
-use 0x2::balance;
-use 0x2::dynamic_object_field;
-use 0x2::object;
-use 0x2::transfer;
-use 0x2::tx_context;
-
- - - - - -## Resource `NftOutput` - -The Stardust NFT output representation. - - -

-struct NftOutput<T> has key
-
- - - -
-Fields - - -
-
- -id: object::UID -
-
- This is a "random" UID, not the NFTID from Stardust. -
-
- -balance: balance::Balance<T> -
-
- The amount of coins held by the output. -
-
- -native_tokens: bag::Bag -
-
- The -Bag holds native tokens, key-ed by the stringified type of the asset. - Example: key: "0xabcded::soon::SOON", value: `Balance<0xabcded::soon::SOON>`. -
-
- -storage_deposit_return_uc: option::Option<storage_deposit_return_unlock_condition::StorageDepositReturnUnlockCondition> -
-
- The storage deposit return unlock condition. -
-
- -timelock_uc: option::Option<timelock_unlock_condition::TimelockUnlockCondition> -
-
- The timelock unlock condition. -
-
- -expiration_uc: option::Option<expiration_unlock_condition::ExpirationUnlockCondition> -
-
- The expiration unlock condition. -
-
- - -
- - - -## Constants - - - - -The NFT dynamic field name. - - -

-const NFT_NAME: vector<u8> = [110, 102, 116];
-
- - - - - -## Function `extract_assets` - -The function extracts assets from a legacy NFT output. - - -

-public fun extract_assets<T>(output: nft_output::NftOutput<T>, ctx: &mut tx_context::TxContext): (balance::Balance<T>, bag::Bag, nft::Nft)
-
- - - -
-Implementation - - -

-public fun extract_assets<T>(mut output: NftOutput<T>, ctx: &mut TxContext): (Balance<T>, Bag, Nft) \{
-    // Load the related Nft object.
-    let nft = load_nft(&mut output);
-
-    // Unpuck the output.
-    let NftOutput \{
-        id,
-        balance: mut balance,
-        native_tokens,
-        storage_deposit_return_uc: mut storage_deposit_return_uc,
-        timelock_uc: mut timelock_uc,
-        expiration_uc: mut expiration_uc
-    } = output;
-
-    // If the output has a timelock unlock condition, then we need to check if the timelock_uc has expired.
-    if (timelock_uc.is_some()) \{
-        timelock_uc.extract().unlock(ctx);
-    };
-
-    // If the output has an expiration unlock condition, then we need to check who can unlock the output.
-    if (expiration_uc.is_some()) \{
-        expiration_uc.extract().unlock(ctx);
-    };
-
-    // If the output has a storage deposit return unlock condition, then we need to return the deposit.
-    if (storage_deposit_return_uc.is_some()) \{
-        storage_deposit_return_uc.extract().unlock(&mut balance, ctx);
-    };
-
-    // Destroy the output.
-    option::destroy_none(timelock_uc);
-    option::destroy_none(expiration_uc);
-    option::destroy_none(storage_deposit_return_uc);
-
-    object::delete(id);
-
-    return (balance, native_tokens, nft)
-}
-
- - - -
- - - -## Function `load_nft` - -Loads the related -Nft object. - - -

-fun load_nft<T>(output: &mut nft_output::NftOutput<T>): nft::Nft
-
- - - -
-Implementation - - -

-fun load_nft<T>(output: &mut NftOutput<T>): Nft \{
-    dynamic_object_field::remove(&mut output.id, NFT_NAME)
-}
-
- - - -
- - - -## Function `attach_nft` - -Utility function to attach an -Alias to an -AliasOutput. - - -

-public fun attach_nft<T>(output: &mut nft_output::NftOutput<T>, nft: nft::Nft)
-
- - - -
-Implementation - - -

-public fun attach_nft<T>(output: &mut NftOutput<T>, nft: Nft) \{
-    dynamic_object_field::add(&mut output.id, NFT_NAME, nft)
-}
-
- - - -
- - - -## Function `receive` - -Utility function to receive an -NftOutput in other Stardust modules. -Other modules in the stardust package can call this function to receive an -NftOutput (alias). - - -

-public(friend) fun receive<T>(parent: &mut object::UID, nft: transfer::Receiving<nft_output::NftOutput<T>>): nft_output::NftOutput<T>
-
- - - -
-Implementation - - -

-public(package) fun receive<T>(parent: &mut UID, nft: Receiving<NftOutput<T>>) : NftOutput<T> \{
-    transfer::receive(parent, nft)
-}
-
- - - -
diff --git a/crates/iota-framework/docs/stardust/stardust_upgrade_label.mdx b/crates/iota-framework/docs/stardust/stardust_upgrade_label.mdx deleted file mode 100644 index 7e7c6bb2d13..00000000000 --- a/crates/iota-framework/docs/stardust/stardust_upgrade_label.mdx +++ /dev/null @@ -1,47 +0,0 @@ ---- -title: Module `0x107a::stardust_upgrade_label` ---- -import Link from '@docusaurus/Link'; - - -All the vested rewards migrated from Stardust are labeled with this label. -It can not be added to an object later after the migration. - - -- [Struct `STARDUST_UPGRADE_LABEL`](#0x107a_stardust_upgrade_label_STARDUST_UPGRADE_LABEL) - - -

-
- - - - - -## Struct `STARDUST_UPGRADE_LABEL` - -Name of the label. - - -

-struct STARDUST_UPGRADE_LABEL has drop
-
- - - -
-Fields - - -
-
- -dummy_field: bool -
-
- -
-
- - -
diff --git a/crates/iota-framework/docs/stardust/storage_deposit_return_unlock_condition.mdx b/crates/iota-framework/docs/stardust/storage_deposit_return_unlock_condition.mdx deleted file mode 100644 index 0a0fc9a5a89..00000000000 --- a/crates/iota-framework/docs/stardust/storage_deposit_return_unlock_condition.mdx +++ /dev/null @@ -1,151 +0,0 @@ ---- -title: Module `0x107a::storage_deposit_return_unlock_condition` ---- -import Link from '@docusaurus/Link'; - - - - -- [Struct `StorageDepositReturnUnlockCondition`](#0x107a_storage_deposit_return_unlock_condition_StorageDepositReturnUnlockCondition) -- [Function `unlock`](#0x107a_storage_deposit_return_unlock_condition_unlock) -- [Function `return_address`](#0x107a_storage_deposit_return_unlock_condition_return_address) -- [Function `return_amount`](#0x107a_storage_deposit_return_unlock_condition_return_amount) - - -

-use 0x2::balance;
-use 0x2::coin;
-use 0x2::transfer;
-use 0x2::tx_context;
-
- - - - - -## Struct `StorageDepositReturnUnlockCondition` - -The Stardust storage deposit return unlock condition. - - -

-struct StorageDepositReturnUnlockCondition has store
-
- - - -
-Fields - - -
-
- -return_address: address -
-
- The address to which the consuming transaction should deposit the amount defined in Return Amount. -
-
- -return_amount: u64 -
-
- The amount of coins the consuming transaction should deposit to the address defined in Return Address. -
-
- - -
- - - -## Function `unlock` - -Check the unlock condition. - - -

-public fun unlock<T>(condition: storage_deposit_return_unlock_condition::StorageDepositReturnUnlockCondition, funding: &mut balance::Balance<T>, ctx: &mut tx_context::TxContext)
-
- - - -
-Implementation - - -

-public fun unlock<T>(condition: StorageDepositReturnUnlockCondition, funding: &mut Balance<T>, ctx: &mut TxContext) \{
-    // Aborts if `funding` is not enough.
-    let return_balance = funding.split(condition.return_amount());
-
-    // Recipient will need to transfer the coin to a normal ed25519 address instead of legacy.
-    public_transfer(from_balance(return_balance, ctx), condition.return_address());
-
-    let StorageDepositReturnUnlockCondition \{
-        return_address: _,
-        return_amount: _,
-    } = condition;
-}
-
- - - -
- - - -## Function `return_address` - -Get the unlock condition's -return_address. - - -

-public fun return_address(condition: &storage_deposit_return_unlock_condition::StorageDepositReturnUnlockCondition): address
-
- - - -
-Implementation - - -

-public fun return_address(condition: &StorageDepositReturnUnlockCondition): address \{
-    condition.return_address
-}
-
- - - -
- - - -## Function `return_amount` - -Get the unlock condition's -return_amount. - - -

-public fun return_amount(condition: &storage_deposit_return_unlock_condition::StorageDepositReturnUnlockCondition): u64
-
- - - -
-Implementation - - -

-public fun return_amount(condition: &StorageDepositReturnUnlockCondition): u64 \{
-    condition.return_amount
-}
-
- - - -
diff --git a/crates/iota-framework/docs/stardust/timelock_unlock_condition.mdx b/crates/iota-framework/docs/stardust/timelock_unlock_condition.mdx deleted file mode 100644 index 87b6b8b1c56..00000000000 --- a/crates/iota-framework/docs/stardust/timelock_unlock_condition.mdx +++ /dev/null @@ -1,153 +0,0 @@ ---- -title: Module `0x107a::timelock_unlock_condition` ---- -import Link from '@docusaurus/Link'; - - - - -- [Struct `TimelockUnlockCondition`](#0x107a_timelock_unlock_condition_TimelockUnlockCondition) -- [Constants](#@Constants_0) -- [Function `unlock`](#0x107a_timelock_unlock_condition_unlock) -- [Function `is_timelocked`](#0x107a_timelock_unlock_condition_is_timelocked) -- [Function `unix_time`](#0x107a_timelock_unlock_condition_unix_time) - - -

-use 0x2::tx_context;
-
- - - - - -## Struct `TimelockUnlockCondition` - -The Stardust timelock unlock condition. - - -

-struct TimelockUnlockCondition has store
-
- - - -
-Fields - - -
-
- -unix_time: u32 -
-
- The unix time (seconds since Unix epoch) starting from which the output can be consumed. -
-
- - -
- - - -## Constants - - - - -The timelock is not expired error. - - -

-const ETimelockNotExpired: u64 = 0;
-
- - - - - -## Function `unlock` - -Check the unlock condition. - - -

-public fun unlock(condition: timelock_unlock_condition::TimelockUnlockCondition, ctx: &tx_context::TxContext)
-
- - - -
-Implementation - - -

-public fun unlock(condition: TimelockUnlockCondition, ctx: &TxContext) \{
-    assert!(!is_timelocked(&condition, ctx), ETimelockNotExpired);
-
-    let TimelockUnlockCondition \{
-        unix_time: _,
-    } = condition;
-}
-
- - - -
- - - -## Function `is_timelocked` - -Check if the output is locked by the -Timelock condition. - - -

-public fun is_timelocked(condition: &timelock_unlock_condition::TimelockUnlockCondition, ctx: &tx_context::TxContext): bool
-
- - - -
-Implementation - - -

-public fun is_timelocked(condition: &TimelockUnlockCondition, ctx: &TxContext): bool \{
-    condition.unix_time() > ((tx_context::epoch_timestamp_ms(ctx) / 1000) as u32)
-}
-
- - - -
- - - -## Function `unix_time` - -Get the unlock condition's -unix_time. - - -

-public fun unix_time(condition: &timelock_unlock_condition::TimelockUnlockCondition): u32
-
- - - -
-Implementation - - -

-public fun unix_time(condition: &TimelockUnlockCondition): u32 \{
-    condition.unix_time
-}
-
- - - -
diff --git a/crates/iota-framework/docs/stardust/utilities.mdx b/crates/iota-framework/docs/stardust/utilities.mdx deleted file mode 100644 index 42977a5e406..00000000000 --- a/crates/iota-framework/docs/stardust/utilities.mdx +++ /dev/null @@ -1,147 +0,0 @@ ---- -title: Module `0x107a::utilities` ---- -import Link from '@docusaurus/Link'; - - - - -- [Constants](#@Constants_0) -- [Function `extract_and_send_to`](#0x107a_utilities_extract_and_send_to) -- [Function `extract`](#0x107a_utilities_extract) -- [Function `extract_`](#0x107a_utilities_extract_) - - -

-use 0x1::ascii;
-use 0x1::type_name;
-use 0x2::bag;
-use 0x2::balance;
-use 0x2::coin;
-use 0x2::transfer;
-use 0x2::tx_context;
-
- - - - - -## Constants - - - - -Returned when trying to extract a -Balance<T> from a -Bag and the balance is zero. - - -

-const EZeroNativeTokenBalance: u64 = 0;
-
- - - - - -## Function `extract_and_send_to` - -Extract a -Balance<T> from a -Bag, create a -Coin out of it and send it to the address. -NOTE: We return the -Bag by value so the function can be called repeatedly in a PTB. - - -

-public fun extract_and_send_to<T>(bag: bag::Bag, to: address, ctx: &mut tx_context::TxContext): bag::Bag
-
- - - -
-Implementation - - -

-public fun extract_and_send_to<T>(mut bag: Bag, to: address, ctx: &mut TxContext): Bag \{
-    let coin = coin::from_balance(extract_<T>(&mut bag), ctx);
-    transfer::public_transfer(coin, to);
-    bag
-}
-
- - - -
- - - -## Function `extract` - -Extract a -Balance<T> from a -Bag and return it. Caller can decide what to do with it. -NOTE: We return the -Bag by value so the function can be called repeatedly in a PTB. - - -

-public fun extract<T>(bag: bag::Bag): (bag::Bag, balance::Balance<T>)
-
- - - -
-Implementation - - -

-public fun extract<T>(mut bag: Bag): (Bag, Balance<T>) \{
-    let balance = extract_<T>(&mut bag);
-    (bag, balance)
-}
-
- - - -
- - - -## Function `extract_` - -Get a -Balance<T> from a -Bag. -Aborts if the balance is zero or if there is no balance for the type -T. - - -

-fun extract_<T>(bag: &mut bag::Bag): balance::Balance<T>
-
- - - -
-Implementation - - -

-fun extract_<T>(bag: &mut Bag): Balance<T> \{
-    let key = type_name::get<T>().into_string();
-
-    // This call aborts if the key doesn't exist.
-    let balance : Balance<T> = bag.remove(key);
-
-    assert!(balance.value() != 0, EZeroNativeTokenBalance);
-
-    balance
-}
-
- - - -
diff --git a/docs/site/docusaurus.config.js b/docs/site/docusaurus.config.js index ff18188ed04..fd41e7072b3 100644 --- a/docs/site/docusaurus.config.js +++ b/docs/site/docusaurus.config.js @@ -76,7 +76,6 @@ const config = { }; }, path.resolve(__dirname, `./src/plugins/descriptions`), - path.resolve(__dirname, `./src/plugins/framework`), ], presets: [ [ diff --git a/docs/site/package.json b/docs/site/package.json index 4d8e055d50a..7dc1083f17b 100644 --- a/docs/site/package.json +++ b/docs/site/package.json @@ -4,8 +4,8 @@ "private": true, "scripts": { "docusaurus": "docusaurus", - "dev": "docusaurus graphql-to-doc; rm '../content/references/iota-api/iota-graphql/reference/generated.md'; git clean -Xdf ../content/references/iota-evm/; ./scripts/get-iota-evm-references.sh; docusaurus start", - "build": "docusaurus graphql-to-doc; rm '../content/references/iota-api/iota-graphql/reference/generated.md'; git clean -Xdf ../content/references/iota-evm/; ./scripts/get-iota-evm-references.sh; docusaurus build", + "dev": "cargo build --manifest-path ../../crates/iota-framework/Cargo.toml; docusaurus graphql-to-doc; rm '../content/references/iota-api/iota-graphql/reference/generated.md'; git clean -Xdf ../content/references/iota-evm/; ./scripts/get-iota-evm-references.sh; docusaurus start", + "build": "cargo build --manifest-path ../../crates/iota-framework/Cargo.toml; docusaurus graphql-to-doc; rm '../content/references/iota-api/iota-graphql/reference/generated.md'; git clean -Xdf ../content/references/iota-evm/; ./scripts/get-iota-evm-references.sh; docusaurus build", "swizzle": "docusaurus swizzle", "deploy": "docusaurus deploy", "clear": "docusaurus clear", diff --git a/docs/site/src/plugins/framework/index.js b/docs/site/src/plugins/framework/index.js deleted file mode 100644 index 9d2bf852d40..00000000000 --- a/docs/site/src/plugins/framework/index.js +++ /dev/null @@ -1,160 +0,0 @@ -// Copyright (c) Mysten Labs, Inc. -// Modifications Copyright (c) 2024 IOTA Stiftung -// SPDX-License-Identifier: Apache-2.0 - -// Plugin copies files from specified directories into the -// references/framework directory. Formats the nav listing -// and processes files so they still work in the crates/.../docs -// directory on github. Source files are created via cargo docs. - -import path from "path"; -import fs from "fs"; - -const FRAMEWORK_PATH = path.join( - __dirname, - "../../../../../crates/iota-framework/docs/iota-framework", -); -const STDLIB_PATH = path.join( - __dirname, - "../../../../../crates/iota-framework/docs/move-stdlib", -); -const IOTASYS_PATH = path.join( - __dirname, - "../../../../../crates/iota-framework/docs/iota-system", -); -const DEEPBOOK_PATH = path.join( - __dirname, - "../../../../../crates/iota-framework/docs/deepbook", -); -const STARDUST_PATH = path.join( - __dirname, - "../../../../../crates/iota-framework/docs/stardust", -); -const DOCS_PATH = path.join( - __dirname, - "../../../../content/references/framework", -); - - -const frameworkPlugin = (context, options) => { - return { - name: "iota-framework-plugin", - - async loadContent() { - // framework folder is added to gitignore, so should only exist locally. - // Clearing the folder programmatically messes up the watch dev build, - // so only do it when the directory is missing. Should never exist on vercel. - if (fs.existsSync(DOCS_PATH)) { - console.log( - "\n******\nSkipping framework doc build. If you want to rebuild, delete the framework folder before restarting the server.\n******", - ); - return; - } else { - fs.mkdirSync(DOCS_PATH); - } - const recurseFiles = (dirPath, files = []) => { - const f = fs.readdirSync(dirPath, { withFileTypes: true }); - // Copy md files from provided directory. - f.forEach((file) => { - const fp = path.join(dirPath, file.name); - if (file.isDirectory()) { - recurseFiles(fp, files); - } else if (file.isFile() && path.extname(file.name) === ".mdx") { - files.push(fp); - } - }); - - return files; - }; - - const frameworkFiles = recurseFiles(FRAMEWORK_PATH); - const stdlibFiles = recurseFiles(STDLIB_PATH); - const deepbookFiles = recurseFiles(DEEPBOOK_PATH); - const iotasysFiles = recurseFiles(IOTASYS_PATH); - const stardustFiles = recurseFiles(STARDUST_PATH); - const allFiles = [ - frameworkFiles, - stdlibFiles, - // deepbookFiles, Disable deepbook docs for now. - iotasysFiles, - stardustFiles, - ]; - allFiles.forEach((theseFiles) => { - theseFiles.forEach((file) => { - const markdown = fs.readFileSync(file, "utf8"); - // .mdx extension in links messes up routing. - // Removing here so linking still works in github crates/docs. - // Remove the backticks from title. - // Remove code blocks without pre's. Render automatically adds - // pre element that messes up formatting. - // Remove empty code blocks because it looks lame. - const filename = file.replace(/.*\/docs\/(.*)$/, `$1`); - const parts = filename.split("/"); - const reMarkdown = markdown - .replace(//g, ``) - .replace( - /(title: .*)Module `(0x[0-9a-f]{1,4}::)(.*)`/g, - `$1 Module $2$3\nsidebar_label: $3\n`, - ) - .replace(/(?)(.*?)<\/code>/gs, `$1`) - .replace(/
<\/code><\/pre>/g, "");
-          const fileWrite = path.join(DOCS_PATH, filename);
-          let newDir = DOCS_PATH;
-
-          // Should work for nested docs, but is currently flat tree.
-          parts.forEach((part) => {
-            if (!part.match(/\.mdx$/)) {
-              // Capitalize lib name for nav.
-              let styledPart = part
-                .split("-")
-                .map(
-                  (word) =>
-                    word.charAt(0).toUpperCase() + word.slice(1).toLowerCase(),
-                )
-                .join(" ");
-
-              newDir = path.join(newDir, part);
-
-              if (!fs.existsSync(newDir)) {
-                fs.mkdirSync(newDir);
-                // Create file that handles nav label. Only run once at dir create.
-                const catfile = path.join(newDir, "_category_.json");
-                fs.writeFile(
-                  catfile,
-                  JSON.stringify({
-                    label: styledPart,
-                    link: {
-                      type: "generated-index",
-                      slug: path.join("/references/framework", part),
-                      description: `Documentation for the modules in the iota/crates/iota-framework/packages/${part} crate. Select a module from the list to see its details.`,
-                    },
-                  }),
-                  "utf8",
-                  (err) => {
-                    if (err) {
-                      console.error(
-                        "An error occurred creating category file:",
-                        err,
-                      );
-                      return;
-                    }
-                  },
-                );
-              }
-            }
-          });
-          fs.writeFileSync(fileWrite, reMarkdown, "utf8", (err) => {
-            if (err) {
-              console.error("An error occurred creating framework file:", err);
-              return;
-            }
-          });
-        });
-      });
-
-      return;
-    },
-  };
-};
-
-module.exports = frameworkPlugin;