Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion book/src/data-model/non-transferable-tokens.md
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ contract update cannot change an existing token's configuration.
| A document type of the token's own contract charging it with `effect: 0` (pay the contract owner) | `NonTransferableTokenPaymentMustBurnError` (10280) | Contract create and update, when the document type is parsed. A document payment refuses it again (`TokenNotTransferableError`, 40726) from the configuration the contract already carries, so a contract that bypassed registration cannot pay with it either |
| A document type of another contract charging it | `TokenNotTransferableError` (40726) | Contract create and update state validation, which already reads the token's contract to check the token exists. Such a cost always pays the contract owner, since another contract's token cannot be burned (10261) |
| `hasShieldedPool: true` | `NonTransferableTokenShieldedPoolError` (10279) | Contract create and update, before anything is charged |
| `marketplaceRules.tradeMode: Tradeable` (protocol version 15) | `NonTransferableTokenTradeableError` (10281) | Contract create and update, before anything is charged, and the batch advanced structure validation of a `TokenConfigUpdate` that makes the token tradeable: the mempool refuses it, and a block charges the signer and bumps the nonce |
| `marketplaceRules.tradeMode: Tradeable` (protocol version 16; refused as not active before it) | `NonTransferableTokenTradeableError` (10281) | Contract create and update, before anything is charged, and the batch advanced structure validation of a `TokenConfigUpdate` that makes the token tradeable: the mempool refuses it, and a block charges the signer and bumps the nonce |

A shielded pool is refused because a note spent inside the pool can be unshielded to any
identity, so shielding and unshielding would move the token between holders. The
Expand Down
14 changes: 8 additions & 6 deletions book/src/data-model/token-marketplace.md
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
# Token Marketplace

From protocol version 15 a token can be tradeable: its holders can sell it to each other on
Platform at a price they set, and anyone can make an offer for it. Nobody has to trust the other
From protocol version 16 a token can be tradeable: its holders can sell it to each other on
Platform at a price they set, and anyone can make an offer for it. Nothing of the market exists
before that version: no escrow tree, no token market contract and no tradeable token. Nobody has
to trust the other
side. The tokens a seller lists and the credits a buyer offers are held in escrow until the order
is filled or cancelled, so a fill always delivers what the order promised.

Expand Down Expand Up @@ -43,8 +45,8 @@ created tradeable becomes tradeable only if its issuer kept the right to change

| Rule | Refused with | Where |
|---|---|---|
| `Tradeable` before protocol version 15 | `StateTransitionNotActiveError` (10603), as `TokenTradeModeTradeable` on a contract and `TokenConfigUpdateMarketplaceTradeModeTradeable` on an update | Contract create and update, and the batch carrying the update, before anything is charged. Software older than protocol version 15 cannot decode the mode, so this is the refusal it gives too |
| `Tradeable` on a [non-transferable token](non-transferable-tokens.md) | `NonTransferableTokenTradeableError` (10281) | Contract create and update before anything is charged, and the advanced structure validation of a `TokenConfigUpdate`, which charges the signer and runs in check_tx too, so the mempool refuses the update |
| `Tradeable` before protocol version 16 | `StateTransitionNotActiveError` (10603), as `TokenTradeModeTradeable` on a contract and `TokenConfigUpdateMarketplaceTradeModeTradeable` on an update | Contract create and update, and the batch carrying the update, before anything is charged. Software older than protocol version 15 cannot decode the mode, so this is the refusal it gives too. Protocol version 15 decodes the mode and gives the same refusal: it has no transitions that place or fill an order, so no contract stores the mode before they exist |
| `Tradeable` on a [non-transferable token](non-transferable-tokens.md), from protocol version 16 | `NonTransferableTokenTradeableError` (10281) | Contract create and update before anything is charged, and the advanced structure validation of a `TokenConfigUpdate`, which charges the signer and runs in check_tx too, so the mempool refuses the update |

A non-transferable token cannot be tradeable because filling a listing or an offer moves the token
from the seller to the buyer, which is the transfer the token refuses. `transferable` is fixed
Expand All @@ -53,8 +55,8 @@ when the token is created, so the trade mode is the only half of the rule an upd
## Where orders and escrow live

Open orders are documents of the token market system contract
(`AE6yYq65VdfGCg2MSyV9vV7cWGiFWjbwBuy7THesDh4e`), registered at genesis from protocol version 15
and inserted by the upgrade to 15. It has two document types, `ask` (a listing) and `bid` (an
(`AE6yYq65VdfGCg2MSyV9vV7cWGiFWjbwBuy7THesDh4e`), registered at genesis from protocol version 16
and inserted by the upgrade to 16. It has two document types, `ask` (a listing) and `bid` (an
offer), each with three indexes:

| Index | Properties | Serves |
Expand Down
6 changes: 3 additions & 3 deletions packages/data-contracts/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -67,9 +67,9 @@ pub enum SystemDataContract {
/// vote poll it funds (protocol version 15). Registered from protocol version 15 on:
/// registered at genesis by chains born at 15 and inserted by the upgrade to 15.
DecisionProposals = 11,
/// The open listings and offers of the token marketplace (protocol version 15). Registered
/// from protocol version 15 on: registered at genesis by chains born at 15 and inserted by
/// the upgrade to 15.
/// The open listings and offers of the token marketplace (protocol version 16). Registered
/// from protocol version 16 on: registered at genesis by chains born at 16 and inserted by
/// the upgrade to 16.
TokenMarket = 12,
}

Expand Down
5 changes: 5 additions & 0 deletions packages/rs-dpp/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,11 @@ tracing = { version = "0.1.41" }
grovedb-commitment-tree = { workspace = true, optional = true }

[dev-dependencies]
# The test platform versions: the token marketplace is tested under one until protocol version
# 16 has tables.
platform-version = { path = "../rs-platform-version", features = [
"mock-versions",
] }
tokio = { version = "1.40", features = ["full"] }
pretty_assertions = { version = "1.4.1" }
dpp = { path = ".", default-features = false, features = [
Expand Down
4 changes: 2 additions & 2 deletions packages/rs-dpp/src/balances/total_tokens_balance/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ pub struct TotalTokensBalance {
/// all the tokens held in token shielded pools (0 before protocol version 14)
pub total_token_shielded_pool_balances: SumTokenAmount,
/// all the tokens the token marketplace holds in escrow for open listings (0 before
/// protocol version 15)
/// protocol version 16)
pub total_token_order_escrow_balances: SumTokenAmount,
}

Expand Down Expand Up @@ -72,7 +72,7 @@ impl TotalTokensBalance {
}

// Every protocol version runs this check. The escrow term is zero below protocol
// version 15, where `calculate_total_tokens_balance` 0 and 1 report none, so this
// version 16, where `calculate_total_tokens_balance` 0 and 1 report none, so this
// refusal and its share of the sum below cannot change their verdict.
if total_token_order_escrow_balances < 0 {
return Err(ProtocolError::CriticalCorruptedCreditsCodeExecution(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -156,10 +156,12 @@ impl TokenConfiguration {
}

/// A tradeable token (`marketplaceRules.tradeMode` `Tradeable`) is admitted from protocol
/// version 15 (`TOKEN_MARKETPLACE_INITIAL_PROTOCOL_VERSION`): below it the mode is refused as
/// not active, the refusal software that predates the marketplace gives by failing to decode
/// it. A tradeable token must also be transferable, since filling a listing or an offer moves
/// the token from one identity to another. Checked on contract create and update.
/// version 16 (`TOKEN_MARKETPLACE_INITIAL_PROTOCOL_VERSION`): below it the mode is
/// refused as not active. Software that predates protocol version 15 gives that refusal by
/// failing to decode the mode; protocol version 15 decodes it and refuses it here, as it has
/// no way to trade a token. A tradeable token must also be transferable, since filling a
/// listing or an offer moves the token from one identity to another. Checked on contract
/// create and update.
pub fn validate_marketplace_rules(
&self,
token_contract_position: TokenContractPosition,
Expand Down Expand Up @@ -1212,6 +1214,7 @@ mod marketplace_rules_tests {
use crate::data_contract::associated_token::token_configuration_item::TokenConfigurationChangeItem;
use crate::data_contract::associated_token::token_marketplace_rules::accessors::v0::TokenMarketplaceRulesV0Setters;
use crate::data_contract::associated_token::token_marketplace_rules::v0::TokenTradeMode;
use platform_version::version::mocks::v5_test::TEST_PROTOCOL_VERSION_5;

fn not_tradeable() -> TokenConfiguration {
TokenConfiguration::V0(TokenConfigurationV0::default_most_restrictive())
Expand All @@ -1229,6 +1232,15 @@ mod marketplace_rules_tests {
PlatformVersion::get(14).expect("expected protocol version 14")
}

/// The protocol version that admits a tradeable token. While it has no tables of its own,
/// the test version that selects the token marketplace stands in for it; once it has them,
/// they are the ones used.
fn protocol_version_admitting_tradeable() -> &'static PlatformVersion {
PlatformVersion::get(TOKEN_MARKETPLACE_INITIAL_PROTOCOL_VERSION)
.or_else(|_| PlatformVersion::get(TEST_PROTOCOL_VERSION_5))
.expect("expected a version that admits a tradeable token")
}

#[test]
fn should_accept_a_token_that_is_not_tradeable_at_every_protocol_version() {
let configurations = BTreeMap::from([(0, not_tradeable())]);
Expand All @@ -1237,39 +1249,52 @@ mod marketplace_rules_tests {
}
}

/// Protocol version 15 decodes the mode, creates the marketplace's state and still refuses
/// the mode: every version below the one that admits it does.
#[test]
fn should_refuse_a_tradeable_token_as_not_active_before_protocol_version_15() {
fn should_refuse_a_tradeable_token_as_not_active_before_protocol_version_16() {
let configurations = BTreeMap::from([(1, tradeable())]);
let result = validate_token_configurations(&configurations, protocol_version_14());
match result.errors.as_slice() {
[error
@ ConsensusError::BasicError(BasicError::StateTransitionNotActiveError(inner))] => {
assert_eq!(inner.state_transition_type(), "TokenTradeModeTradeable");
assert_eq!(inner.current_protocol_version(), 14);
assert_eq!(
inner.required_protocol_version(),
TOKEN_MARKETPLACE_INITIAL_PROTOCOL_VERSION
);
assert_eq!(error.code(), 10603);
let protocol_version_15 = PlatformVersion::get(15).expect("expected protocol version 15");
for platform_version in [protocol_version_14(), protocol_version_15] {
let result = validate_token_configurations(&configurations, platform_version);
match result.errors.as_slice() {
[error @ ConsensusError::BasicError(BasicError::StateTransitionNotActiveError(
inner,
))] => {
assert_eq!(inner.state_transition_type(), "TokenTradeModeTradeable");
assert_eq!(
inner.current_protocol_version(),
platform_version.protocol_version
);
assert_eq!(
inner.required_protocol_version(),
TOKEN_MARKETPLACE_INITIAL_PROTOCOL_VERSION
);
assert_eq!(inner.required_protocol_version(), 16);
assert_eq!(error.code(), 10603);
}
other => panic!("expected StateTransitionNotActiveError, got {other:?}"),
}
other => panic!("expected StateTransitionNotActiveError, got {other:?}"),
}
}

#[test]
fn should_accept_a_tradeable_transferable_token_from_protocol_version_15() {
fn should_accept_a_tradeable_transferable_token_from_protocol_version_16() {
let configurations = BTreeMap::from([(0, tradeable())]);
assert!(
validate_token_configurations(&configurations, PlatformVersion::latest()).is_valid()
);
assert!(validate_token_configurations(
&configurations,
protocol_version_admitting_tradeable()
)
.is_valid());
}

#[test]
fn should_refuse_a_tradeable_non_transferable_token_with_error_10281() {
let mut configuration = tradeable();
configuration.set_transferable(false);
let configurations = BTreeMap::from([(3, configuration)]);
let result = validate_token_configurations(&configurations, PlatformVersion::latest());
let result =
validate_token_configurations(&configurations, protocol_version_admitting_tradeable());
match result.errors.as_slice() {
[error @ ConsensusError::BasicError(BasicError::NonTransferableTokenTradeableError(
inner,
Expand All @@ -1288,12 +1313,10 @@ mod marketplace_rules_tests {
fn should_refuse_making_a_non_transferable_token_tradeable_through_its_configuration_item() {
let mut configuration = not_tradeable();
configuration.set_transferable(false);
let platform_version = protocol_version_admitting_tradeable();

let proposed = configuration.validate_trade_mode(
&TokenTradeMode::Tradeable,
0,
PlatformVersion::latest(),
);
let proposed =
configuration.validate_trade_mode(&TokenTradeMode::Tradeable, 0, platform_version);
assert!(matches!(
proposed.errors.as_slice(),
[ConsensusError::BasicError(
Expand All @@ -1304,7 +1327,7 @@ mod marketplace_rules_tests {
configuration.apply_token_configuration_item(
TokenConfigurationChangeItem::MarketplaceTradeMode(TokenTradeMode::Tradeable),
);
let applied = configuration.validate_marketplace_rules(0, PlatformVersion::latest());
let applied = configuration.validate_marketplace_rules(0, platform_version);
assert_eq!(applied.errors, proposed.errors);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,8 +29,8 @@ pub enum TokenTradeMode {
NotTradeable,
/// Holders may list the token at a price and make offers for it: listed tokens and offered
/// credits are held in escrow until the order is filled or cancelled. Admitted from protocol
/// version 15 (`TOKEN_MARKETPLACE_INITIAL_PROTOCOL_VERSION`), and only on a transferable
/// token, since every fill moves the token from one identity to another.
/// version 16 (`TOKEN_MARKETPLACE_INITIAL_PROTOCOL_VERSION`), and only on a
/// transferable token, since every fill moves the token from one identity to another.
Tradeable,
}

Expand Down
20 changes: 14 additions & 6 deletions packages/rs-dpp/src/system_data_contracts.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1817,15 +1817,18 @@ mod token_market_tests {
use crate::document::transfer::Transferable;
use crate::nft::TradeMode;
use crate::system_data_contracts::token_market_contract::v1::document_types::{ask, bid};
use platform_version::version::mocks::v5_test::TEST_PLATFORM_V5;

/// The order types are what the marketplace transitions rely on: only they create orders,
/// orders stay mutable and deletable so a partial fill can rewrite them and a close can
/// delete them with their storage flags, every integer is a signed 8-byte value, and the
/// `depth` index sums what the order holds in escrow.
#[test]
fn should_load_the_order_types_the_marketplace_writes() {
// The token marketplace starts with protocol version 16, which has no tables yet: the
// test version that selects it stands in.
let contract =
load_system_data_contract(SystemDataContract::TokenMarket, PlatformVersion::latest())
load_system_data_contract(SystemDataContract::TokenMarket, &TEST_PLATFORM_V5)
.expect("the token market contract loads with full validation");
assert_eq!(contract.id(), token_market_contract::ID);
assert_eq!(contract.owner_id(), token_market_contract::OWNER_ID);
Expand Down Expand Up @@ -1908,10 +1911,15 @@ mod token_market_tests {
}

#[test]
fn should_not_exist_before_protocol_version_15() {
let platform_version = PlatformVersion::get(14).expect("protocol version 14");
assert!(
load_system_data_contract(SystemDataContract::TokenMarket, platform_version).is_err()
);
fn should_not_exist_before_protocol_version_16() {
for protocol_version in [14, 15] {
let platform_version =
PlatformVersion::get(protocol_version).expect("expected the protocol version");
assert!(
load_system_data_contract(SystemDataContract::TokenMarket, platform_version)
.is_err(),
"protocol version {protocol_version}"
);
}
}
}
Loading
Loading