Skip to content

Commit

Permalink
Tos data reduce (#101)
Browse files Browse the repository at this point in the history
* Stream deconstruct WIP

* Minimize stream storage load

* Fix comment

* Minimize tos data on loads

* Generate schema
  • Loading branch information
orkunkl authored Dec 4, 2024
1 parent 2225efd commit bf92af4
Show file tree
Hide file tree
Showing 9 changed files with 94 additions and 39 deletions.
44 changes: 31 additions & 13 deletions contracts/stream/src/contract.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,9 @@ use crate::stream::{compute_shares_amount, sync_stream, sync_stream_status};
use crate::{circuit_ops, ContractError};
use core::str;
use cosmwasm_std::{
attr, entry_point, to_json_binary, Attribute, BankMsg, Binary, Coin, CosmosMsg, Decimal256,
Deps, DepsMut, Env, MessageInfo, Order, Response, StdError, StdResult, Timestamp, Uint128,
Uint256,
attr, entry_point, to_json_binary, Addr, Attribute, BankMsg, Binary, Coin, CosmosMsg,
Decimal256, Deps, DepsMut, Env, MessageInfo, Order, Response, StdError, StdResult, Timestamp,
Uint128, Uint256,
};
use cw2::{ensure_from_older_version, set_contract_version};
use cw_storage_plus::Bound;
Expand All @@ -24,7 +24,7 @@ use streamswap_utils::to_uint256;
use crate::pool::pool_operations;
use crate::state::{
CONTROLLER_PARAMS, CREATOR_VESTING, POSITIONS, POST_STREAM, STREAM_INFO, STREAM_STATE,
SUBSCRIBER_VESTING,
SUBSCRIBER_VESTING, TOS, TOS_SIGNED,
};
use crate::vesting::vesting_operations;
use streamswap_types::controller::{CreatePool, Params as ControllerParams, PoolConfig};
Expand Down Expand Up @@ -95,13 +95,7 @@ pub fn instantiate(
);
STREAM_STATE.save(deps.storage, &stream_state)?;

let stream_info = StreamInfo::new(
stream_admin.clone(),
name.clone(),
treasury.clone(),
url,
tos_version,
);
let stream_info = StreamInfo::new(stream_admin.clone(), name.clone(), treasury.clone(), url);
STREAM_INFO.save(deps.storage, &stream_info)?;

let post_stream_actions =
Expand All @@ -111,6 +105,8 @@ pub fn instantiate(
let threshold_state = ThresholdState::new();
threshold_state.set_threshold_if_any(threshold, deps.storage)?;

TOS.save(deps.storage, &tos_version)?;

let mut attrs = vec![
attr("action", "instantiate"),
attr("name", name),
Expand Down Expand Up @@ -322,16 +318,18 @@ pub fn execute_subscribe(
sync_stream(&mut stream_state, env.block.time);
new_shares = compute_shares_amount(&stream_state, uint256_in_amount, false);
// new positions do not update purchase as it has no effect on distribution
let stream_info = STREAM_INFO.load(deps.storage)?;
let new_position = Position::new(
info.sender.clone(),
uint256_in_amount,
new_shares,
Some(stream_state.dist_index),
env.block.time,
stream_info.tos_version.clone(),
);
POSITIONS.save(deps.storage, &info.sender, &new_position)?;

// Save signed TOS
let tos_version = TOS.load(deps.storage)?;
TOS_SIGNED.save(deps.storage, &info.sender, &tos_version)?;
}
Some(mut position) => {
if position.owner != info.sender {
Expand Down Expand Up @@ -746,6 +744,16 @@ pub fn query(deps: Deps, env: Env, msg: QueryMsg) -> StdResult<Binary> {
QueryMsg::AveragePrice {} => to_json_binary(&query_average_price(deps, env)?),
QueryMsg::LastStreamedPrice {} => to_json_binary(&query_last_streamed_price(deps, env)?),
QueryMsg::Threshold {} => to_json_binary(&query_threshold_state(deps, env)?),
QueryMsg::ToS { addr } => {
if let Some(addr) = addr {
to_json_binary(&query_tos_signed(
deps,
&deps.api.addr_validate(addr.as_str())?,
)?)
} else {
to_json_binary(&query_tos(deps)?)
}
}
}
}
pub fn query_params(deps: Deps) -> StdResult<ControllerParams> {
Expand Down Expand Up @@ -844,3 +852,13 @@ pub fn query_threshold_state(deps: Deps, _env: Env) -> Result<Option<Uint256>, S
let threshold = threshold_state.get_threshold(deps.storage)?;
Ok(threshold)
}

pub fn query_tos(deps: Deps) -> StdResult<String> {
let tos = TOS.load(deps.storage)?;
Ok(tos)
}

pub fn query_tos_signed(deps: Deps, addr: &Addr) -> StdResult<String> {
let tos = TOS_SIGNED.load(deps.storage, addr)?;
Ok(tos)
}
5 changes: 2 additions & 3 deletions contracts/stream/src/state.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,6 @@ pub const STREAM_INFO: Item<StreamInfo> = Item::new("si");
// Post Stream Action Related Information
pub const POST_STREAM: Item<PostStreamActions> = Item::new("ps");

pub const TOS: Item<String> = Item::new("tos");

// Subscriber Vesting (owner_addr) -> (contract_addr)
pub const SUBSCRIBER_VESTING: Map<Addr, Addr> = Map::new("sub_vest");

Expand All @@ -25,6 +23,7 @@ pub const CREATOR_VESTING: Item<Addr> = Item::new("cr_vest");
// Position (stream_id, owner_addr) -> Position
pub const POSITIONS: Map<&Addr, Position> = Map::new("positions");

/// Terms and services ipfs link signature signed by user
/// Terms and services ipfs link
pub const TOS: Item<String> = Item::new("tos");
/// Both for creator and subscriber
pub const TOS_SIGNED: Map<&Addr, String> = Map::new("tos_signed");
20 changes: 14 additions & 6 deletions packages/types/src/stream/msg.rs
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,8 @@ pub enum QueryMsg {
LastStreamedPrice {},
#[returns(Uint128)]
Threshold {},
#[returns(String)]
ToS { addr: Option<String> },
}

#[cw_serde]
Expand Down Expand Up @@ -140,18 +142,19 @@ pub struct PositionResponse {
pub owner: String,
/// Current amount of tokens in buy pool
pub in_balance: Uint256,
/// Shares amount position owns
pub shares: Uint256,
// Index is used to calculate the distribution a position has
/// Index is used to calculate the distribution a position has
pub index: Decimal256,
// Last_updated_time is the time when the position was last updated
/// Last_updated_time is the time when the position was last updated
pub last_updated: Timestamp,
// Total amount of `token_out` purchased in tokens at latest calculation
/// Total amount of `token_out` purchased in tokens at latest calculation
pub purchased: Uint256,
// Pending purchased accumulates purchases after decimal truncation
/// Pending purchased accumulates purchases after decimal truncation
pub pending_purchase: Decimal256,
// Total amount of `token_in` spent tokens at latest calculation
/// Total amount of `token_in` spent tokens at latest calculation
pub spent: Uint256,
// Exit date of the position
/// Exit date of the position
pub exit_date: Timestamp,
}

Expand All @@ -170,5 +173,10 @@ pub struct LatestStreamedPriceResponse {
pub current_streamed_price: Decimal256,
}

#[cw_serde]
pub struct TosResponse {
pub tos: String,
}

#[cw_serde]
pub struct MigrateMsg {}
4 changes: 0 additions & 4 deletions packages/types/src/stream/position.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,6 @@ pub struct Position {
pub spent: Uint256,
// Exit date of the position
pub exit_date: Timestamp,
// signed tos version
pub tos_version: String,
}

impl Position {
Expand All @@ -31,7 +29,6 @@ impl Position {
shares: Uint256,
index: Option<Decimal256>,
last_updated: Timestamp,
tos_version: String,
) -> Self {
Position {
owner,
Expand All @@ -43,7 +40,6 @@ impl Position {
pending_purchase: Decimal256::zero(),
spent: Uint256::zero(),
exit_date: Timestamp::from_nanos(0),
tos_version,
}
}
}
11 changes: 1 addition & 10 deletions packages/types/src/stream/stream.rs
Original file line number Diff line number Diff line change
Expand Up @@ -84,24 +84,15 @@ pub struct StreamInfo {
/// Stream admin address, where the stream creator can manage the stream, like canceling it in waiting status
/// or finalizing it in ended status
pub url: Option<String>,
// Tos version
pub tos_version: String,
}

impl StreamInfo {
pub fn new(
stream_admin: Addr,
name: String,
treasury: Addr,
url: Option<String>,
tos_version: String,
) -> Self {
pub fn new(stream_admin: Addr, name: String, treasury: Addr, url: Option<String>) -> Self {
StreamInfo {
stream_admin,
name,
treasury,
url,
tos_version,
}
}
}
Expand Down
21 changes: 21 additions & 0 deletions tests/src/tests/streamswap_tests/subscribe.rs
Original file line number Diff line number Diff line change
Expand Up @@ -137,6 +137,27 @@ mod subscribe {
assert_eq!(position.in_balance, Uint256::from(150u128));
assert_eq!(position.spent, Uint256::zero());

// check tos
let tos: String = app
.wrap()
.query_wasm_smart(
Addr::unchecked(stream_swap_contract_address.clone()),
&StreamSwapQueryMsg::ToS { addr: None },
)
.unwrap();

// query position
let tos_signed: String = app
.wrap()
.query_wasm_smart(
Addr::unchecked(stream_swap_contract_address.clone()),
&StreamSwapQueryMsg::ToS {
addr: Some(position.owner),
},
)
.unwrap();
assert_eq!(tos, tos_signed);

// Update stream
app.set_block(BlockInfo {
height: 2_200,
Expand Down
19 changes: 18 additions & 1 deletion ts/types/StreamSwapStream.client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@

import { CosmWasmClient, SigningCosmWasmClient, ExecuteResult } from "@cosmjs/cosmwasm-stargate";
import { StdFee } from "@cosmjs/amino";
import { Timestamp, Uint64, Schedule, Uint128, PoolConfig, Uint256, Binary, InstantiateMsg, VestingConfig, Coin, ExecuteMsg, CreatePool, QueryMsg, Decimal256, AveragePriceResponse, LatestStreamedPriceResponse, PositionsResponse, PositionResponse, Addr, Params, Status, StreamResponse } from "./StreamSwapStream.types";
import { Timestamp, Uint64, Schedule, Uint128, PoolConfig, Uint256, Binary, InstantiateMsg, VestingConfig, Coin, ExecuteMsg, CreatePool, QueryMsg, Decimal256, AveragePriceResponse, LatestStreamedPriceResponse, PositionsResponse, PositionResponse, Addr, Params, Status, StreamResponse, String } from "./StreamSwapStream.types";
export interface StreamSwapStreamReadOnlyInterface {
contractAddress: string;
params: () => Promise<Params>;
Expand All @@ -26,6 +26,11 @@ export interface StreamSwapStreamReadOnlyInterface {
averagePrice: () => Promise<AveragePriceResponse>;
lastStreamedPrice: () => Promise<LatestStreamedPriceResponse>;
threshold: () => Promise<Uint128>;
toS: ({
addr
}: {
addr?: string;
}) => Promise<String>;
}
export class StreamSwapStreamQueryClient implements StreamSwapStreamReadOnlyInterface {
client: CosmWasmClient;
Expand All @@ -41,6 +46,7 @@ export class StreamSwapStreamQueryClient implements StreamSwapStreamReadOnlyInte
this.averagePrice = this.averagePrice.bind(this);
this.lastStreamedPrice = this.lastStreamedPrice.bind(this);
this.threshold = this.threshold.bind(this);
this.toS = this.toS.bind(this);
}

params = async (): Promise<Params> => {
Expand Down Expand Up @@ -93,6 +99,17 @@ export class StreamSwapStreamQueryClient implements StreamSwapStreamReadOnlyInte
threshold: {}
});
};
toS = async ({
addr
}: {
addr?: string;
}): Promise<String> => {
return this.client.queryContractSmart(this.contractAddress, {
to_s: {
addr
}
});
};
}
export interface StreamSwapStreamInterface extends StreamSwapStreamReadOnlyInterface {
contractAddress: string;
Expand Down
2 changes: 1 addition & 1 deletion ts/types/StreamSwapStream.message-composer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
import { MsgExecuteContractEncodeObject } from "@cosmjs/cosmwasm-stargate";
import { MsgExecuteContract } from "cosmjs-types/cosmwasm/wasm/v1/tx";
import { toUtf8 } from "@cosmjs/encoding";
import { Timestamp, Uint64, Schedule, Uint128, PoolConfig, Uint256, Binary, InstantiateMsg, VestingConfig, Coin, ExecuteMsg, CreatePool, QueryMsg, Decimal256, AveragePriceResponse, LatestStreamedPriceResponse, PositionsResponse, PositionResponse, Addr, Params, Status, StreamResponse } from "./StreamSwapStream.types";
import { Timestamp, Uint64, Schedule, Uint128, PoolConfig, Uint256, Binary, InstantiateMsg, VestingConfig, Coin, ExecuteMsg, CreatePool, QueryMsg, Decimal256, AveragePriceResponse, LatestStreamedPriceResponse, PositionsResponse, PositionResponse, Addr, Params, Status, StreamResponse, String } from "./StreamSwapStream.types";
export interface StreamSwapStreamMsg {
contractAddress: string;
sender: string;
Expand Down
7 changes: 6 additions & 1 deletion ts/types/StreamSwapStream.types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,10 @@ export type QueryMsg = {
last_streamed_price: {};
} | {
threshold: {};
} | {
to_s: {
addr?: string | null;
};
};
export type Decimal256 = string;
export interface AveragePriceResponse {
Expand Down Expand Up @@ -153,4 +157,5 @@ export interface StreamResponse {
stream_admin: string;
treasury: string;
url?: string | null;
}
}
export type String = string;

0 comments on commit bf92af4

Please sign in to comment.