Skip to content

Issue 382 campaign routes #411

New issue

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

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

Already on GitHub? Sign in to your account

Merged
merged 64 commits into from
Aug 10, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
64 commits
Select commit Hold shift + click to select a range
3661ca2
committing current progress
simzzz May 28, 2021
413149f
Merge branch 'aip-61-adex-v5' into v5-modify-submit-campaigns
simzzz May 28, 2021
8c4d687
fixed some more errors
simzzz May 31, 2021
58c61aa
more error fixes
simzzz May 31, 2021
70ff87c
Progress w/out tests
simzzz Jun 8, 2021
f7dae5b
fixed typo
simzzz Jun 10, 2021
0f40016
Refactoring + changes to the way the remaining for all campaigns is r…
simzzz Jun 10, 2021
33f0e3e
added CampaignCreateResponse
simzzz Jun 10, 2021
084f6e6
Merge branch 'aip-61-adex-v5' into v5-modify-submit-campaigns
simzzz Jun 11, 2021
475b8db
More changes to budget/redis operations + fixed problems from PR review
simzzz Jun 11, 2021
60efa4a
more changes to updating remaining
simzzz Jun 11, 2021
688a51c
sentry - db - re-export campaign module
elpiel Jun 12, 2021
7b93256
sentry - db - campaign - fix fetch_campaign
elpiel Jun 13, 2021
f42d5b6
sentry - middleware - campaign - CampaignLoad
elpiel Jun 13, 2021
1b8cd75
added regex for campaign update route
simzzz Jun 14, 2021
efb30f9
Merge branch 'issue-381-accounting-db' into v5-modify-submit-campaigns
simzzz Jun 15, 2021
be47fe2
sentry - route - campaign - insert events
elpiel Jun 15, 2021
00abea5
primitives - sentry - remove Events:
elpiel Jun 15, 2021
57116cc
Accounting messages + First integration tests
simzzz Jun 15, 2021
f4e0949
fixed some unwraps
simzzz Jun 16, 2021
825d6cb
more fixes
simzzz Jun 22, 2021
5f0e1c9
sentry - routes - channel - remove insert_events
elpiel Jun 22, 2021
5fd05db
Merge branch 'issue-382-campaign-routes' into v5-modify-submit-campaigns
simzzz Jun 22, 2021
115b7b0
sentry - clean up Events code in Channel & access
elpiel Jun 23, 2021
67a9462
Merge branch 'aip61-targeting-rules-use-unified-num' into issue-382-c…
elpiel Jun 23, 2021
2d73644
Merge branch 'aip-61-adex-v5' into issue-382-campaign-routes
elpiel Jun 24, 2021
bcf3d9a
Merge branch 'issue-382-campaign-routes' into issue-382-campaign-inse…
elpiel Jun 24, 2021
067b3af
fixed remaining issues in PR
simzzz Jun 29, 2021
9fd4f4a
Included MGET for getting multiple remainings at once
simzzz Jun 30, 2021
9380089
fixed failing test
simzzz Jun 30, 2021
219e3f0
cargofmt + some refactoring + used MutatedCampaign object in more places
simzzz Jun 30, 2021
ccb1eac
sentry - Cargo - add `postgres-types` `derive` feature
elpiel Jun 30, 2021
99807db
sentry - migrations - accounting - flat structure
elpiel Jun 30, 2021
a3eb101
sentry - db - accounting follows flat struture
elpiel Jun 30, 2021
187d198
Merge branch 'issue-382-campaign-routes' into v5-modify-submit-campaigns
simzzz Jul 2, 2021
ad2d585
Finished with PR changes requested
simzzz Jul 6, 2021
5cb26ef
sentry - prefix campaign routes with `/v5/`
elpiel Jul 9, 2021
4f23861
PR changes
simzzz Jul 9, 2021
be36327
sentry - db - accounting - spend_amount with delta Balances
elpiel Jul 12, 2021
6f51c70
sentry - routes - insert_events route
elpiel Jul 12, 2021
b81584b
Merge branch 'aip-61-adex-v5' into issue-382-campaign-routes
elpiel Jul 12, 2021
0082a35
Merge branch 'issue-382-campaign-routes' into v5-modify-submit-campaigns
simzzz Jul 12, 2021
8fcef13
sentry - routes - modify campaign
elpiel Jul 13, 2021
b664dd1
sentry - db - campaign - fix doc comment
elpiel Jul 13, 2021
a2cabe2
Merge branch 'issue-382-campaign-routes' into issue-382-campaign-inse…
elpiel Jul 14, 2021
10deba9
sentry - mod test_util - setup_dummy_app helper fn
elpiel Aug 4, 2021
88c3243
sentry - db - campaign - CampaignRemaining redis struct
elpiel Aug 4, 2021
3ca6ab5
primitives - sentry - impl From<Campaign> for CreateCampaign
elpiel Aug 4, 2021
11dc715
primitives - validator - From<Address> for ValidatorID
elpiel Aug 4, 2021
07d9c74
primitives - sentry - accounting - Balances - add spender/earner
elpiel Aug 9, 2021
d80e109
sentry - Applicaiton - add CampaignRemaining to app
elpiel Aug 9, 2021
e1a245e
sentry - db - CampaignRemaining - MGET guard against empty vec of cam…
elpiel Aug 9, 2021
9a94c5f
sentry - routes - campaign create/modify - more checks & tests
elpiel Aug 9, 2021
2752dea
fix PR comments
elpiel Aug 9, 2021
5177217
sentry - db - make pub insert_accounting
elpiel Aug 9, 2021
75a5a5f
sentry - routes - campaign - get_delta_budget - fix logic & naming
elpiel Aug 9, 2021
19ccd17
Merge pull request #418 from AdExNetwork/redis-and-tests
elpiel Aug 9, 2021
c6c63bc
Merge pull request #408 from AdExNetwork/v5-modify-submit-campaigns
elpiel Aug 9, 2021
fa39cb1
Merge branch 'issue-382-campaign-routes' into issue-382-campaign-inse…
elpiel Aug 9, 2021
70376b3
Fix merge issues & run rustfmt
elpiel Aug 9, 2021
1fca9ec
fix clippy warnings
elpiel Aug 10, 2021
05ac2b0
rustfmt
elpiel Aug 10, 2021
598ab52
sentry - routes - camiang insert events - use CampaignRemaining
elpiel Aug 10, 2021
30b375d
Merge pull request #413 from AdExNetwork/issue-382-campaign-insert-ev…
elpiel Aug 10, 2021
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
13 changes: 13 additions & 0 deletions Cargo.lock

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

4 changes: 2 additions & 2 deletions adapter/src/dummy.rs
Original file line number Diff line number Diff line change
Expand Up @@ -92,8 +92,8 @@ impl Adapter for DummyAdapter {
Ok(())
}

fn whoami(&self) -> &ValidatorId {
&self.identity
fn whoami(&self) -> ValidatorId {
self.identity
}

fn sign(&self, state_root: &str) -> AdapterResult<String, Self::AdapterError> {
Expand Down
14 changes: 7 additions & 7 deletions adapter/src/ethereum.rs
Original file line number Diff line number Diff line change
Expand Up @@ -149,8 +149,8 @@ impl Adapter for EthereumAdapter {
Ok(())
}

fn whoami(&self) -> &ValidatorId {
&self.address
fn whoami(&self) -> ValidatorId {
self.address
}

fn sign(&self, state_root: &str) -> AdapterResult<String, Self::AdapterError> {
Expand Down Expand Up @@ -263,7 +263,7 @@ impl Adapter for EthereumAdapter {
address: self.whoami().to_checksum(),
};

ewt_sign(&wallet, &self.keystore_pwd, &payload)
ewt_sign(wallet, &self.keystore_pwd, &payload)
.map_err(|err| AdapterError::Adapter(Error::SignMessage(err).into()))
}

Expand Down Expand Up @@ -401,8 +401,8 @@ fn hash_message(message: &[u8]) -> [u8; 32] {
let message_length = message.len();

let mut result = Keccak::new_keccak256();
result.update(&format!("{}{}", eth, message_length).as_bytes());
result.update(&message);
result.update(format!("{}{}", eth, message_length).as_bytes());
result.update(message);

let mut res: [u8; 32] = [0; 32];
result.finalize(&mut res);
Expand Down Expand Up @@ -453,7 +453,7 @@ pub fn ewt_sign(
base64::URL_SAFE_NO_PAD,
);
let message = Message::from(hash_message(
&format!("{}.{}", header_encoded, payload_encoded).as_bytes(),
format!("{}.{}", header_encoded, payload_encoded).as_bytes(),
));
let signature: Signature = signer
.sign(password, &message)
Expand All @@ -475,7 +475,7 @@ pub fn ewt_verify(
token: &str,
) -> Result<VerifyPayload, EwtVerifyError> {
let message = Message::from(hash_message(
&format!("{}.{}", header_encoded, payload_encoded).as_bytes(),
format!("{}.{}", header_encoded, payload_encoded).as_bytes(),
));

let decoded_signature = base64::decode_config(&token, base64::URL_SAFE_NO_PAD)
Expand Down
2 changes: 1 addition & 1 deletion adview-manager/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -172,7 +172,7 @@ fn get_unit_html(
) -> String {
let image_url = normalize_url(&ad_unit.media_url);

let element_html = if is_video(&ad_unit) {
let element_html = if is_video(ad_unit) {
video_html(on_load, size, &image_url, &ad_unit.media_mime)
} else {
image_html(on_load, size, &image_url)
Expand Down
2 changes: 1 addition & 1 deletion lib/protocol-eth
2 changes: 1 addition & 1 deletion primitives/src/adapter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ pub trait Adapter: Send + Sync + fmt::Debug + Clone {
fn unlock(&mut self) -> AdapterResult<(), Self::AdapterError>;

/// Get Adapter whoami
fn whoami(&self) -> &ValidatorId;
fn whoami(&self) -> ValidatorId;

/// Signs the provided state_root
fn sign(&self, state_root: &str) -> AdapterResult<String, Self::AdapterError>;
Expand Down
2 changes: 1 addition & 1 deletion primitives/src/big_num.rs
Original file line number Diff line number Diff line change
Expand Up @@ -243,7 +243,7 @@ impl TryFrom<&str> for BigNum {
type Error = super::DomainError;

fn try_from(num: &str) -> Result<Self, Self::Error> {
let big_uint = BigUint::from_str(&num)
let big_uint = BigUint::from_str(num)
.map_err(|err| super::DomainError::InvalidArgument(err.to_string()))?;

Ok(Self(big_uint))
Expand Down
4 changes: 2 additions & 2 deletions primitives/src/campaign.rs
Original file line number Diff line number Diff line change
Expand Up @@ -195,7 +195,7 @@ impl Campaign {
}
}

/// Matches the Channel.leader to the Campaign.spec.leader
/// Matches the Channel.leader to the Campaign.validators.leader
/// If they match it returns `Some`, otherwise, it returns `None`
pub fn leader(&self) -> Option<&'_ ValidatorDesc> {
self.validators.find(&self.channel.leader)
Expand Down Expand Up @@ -318,7 +318,7 @@ pub mod validators {
}

pub fn iter(&self) -> Iter<'_> {
Iter::new(&self)
Iter::new(self)
}
}

Expand Down
2 changes: 1 addition & 1 deletion primitives/src/campaign_validator.rs
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ impl Validator for Campaign {
return Err(Validation::UnlistedValidator.into());
}

if !creator_listed(&self, &config.creators_whitelist) {
if !creator_listed(self, &config.creators_whitelist) {
return Err(Validation::UnlistedCreator.into());
}

Expand Down
6 changes: 3 additions & 3 deletions primitives/src/channel.rs
Original file line number Diff line number Diff line change
Expand Up @@ -238,9 +238,9 @@ impl SpecValidators {

pub fn find(&self, validator_id: &ValidatorId) -> Option<SpecValidator<'_>> {
if &self.leader().id == validator_id {
Some(SpecValidator::Leader(&self.leader()))
Some(SpecValidator::Leader(self.leader()))
} else if &self.follower().id == validator_id {
Some(SpecValidator::Follower(&self.follower()))
Some(SpecValidator::Follower(self.follower()))
} else {
None
}
Expand All @@ -257,7 +257,7 @@ impl SpecValidators {
}

pub fn iter(&self) -> Iter<'_> {
Iter::new(&self)
Iter::new(self)
}
}

Expand Down
98 changes: 80 additions & 18 deletions primitives/src/sentry.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
use crate::{
targeting::Rules,
validator::{ApproveState, Heartbeat, MessageTypes, NewState, Type as MessageType},
Address, BalancesMap, BigNum, Channel, ChannelId, ValidatorId, IPFS,
Address, BigNum, Channel, ChannelId, ValidatorId, IPFS,
};
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
Expand Down Expand Up @@ -127,19 +126,6 @@ pub enum Event {
ad_slot: Option<IPFS>,
referrer: Option<String>,
},
/// only the creator can send this event
#[serde(rename_all = "camelCase")]
UpdateTargeting { targeting_rules: Rules },
/// Closes the `Campaign`
/// only the creator can send this event
#[serde(rename_all = "camelCase")]
Close,
/// TODO: AIP#61 Check and explain who can send this event as well as when it can be received
/// A map of earners which gets merged in the `spender::Aggregate`
/// NOTE: Does **not** contain any fees!
/// This even can be used to pay to yourself, but this is irrelevant as it's your funds you are paying yourself.
#[serde(rename_all = "camelCase")]
Pay { payout: BalancesMap },
}

impl Event {
Expand All @@ -161,9 +147,6 @@ impl AsRef<str> for Event {
match *self {
Event::Impression { .. } => "IMPRESSION",
Event::Click { .. } => "CLICK",
Event::UpdateTargeting { .. } => "UPDATE_TARGETING",
Event::Close => "CLOSE",
Event::Pay { .. } => "PAY",
}
}
}
Expand Down Expand Up @@ -377,6 +360,85 @@ pub mod campaign_create {
}
}
}

/// This implementation helps with test setup
/// **NOTE:** It erases the CampaignId, since the creation of the campaign gives it's CampaignId
impl From<Campaign> for CreateCampaign {
fn from(campaign: Campaign) -> Self {
Self {
channel: campaign.channel,
creator: campaign.creator,
budget: campaign.budget,
validators: campaign.validators,
title: campaign.title,
pricing_bounds: campaign.pricing_bounds,
event_submission: campaign.event_submission,
ad_units: campaign.ad_units,
targeting_rules: campaign.targeting_rules,
created: campaign.created,
active: campaign.active,
}
}
}

// All editable fields stored in one place, used for checking when a budget is changed
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct ModifyCampaign {
pub budget: Option<UnifiedNum>,
pub validators: Option<Validators>,
pub title: Option<String>,
pub pricing_bounds: Option<PricingBounds>,
pub event_submission: Option<EventSubmission>,
pub ad_units: Option<Vec<AdUnit>>,
pub targeting_rules: Option<Rules>,
}

impl ModifyCampaign {
pub fn from_campaign(campaign: Campaign) -> Self {
ModifyCampaign {
budget: Some(campaign.budget),
validators: Some(campaign.validators),
title: campaign.title,
pricing_bounds: campaign.pricing_bounds,
event_submission: campaign.event_submission,
ad_units: Some(campaign.ad_units),
targeting_rules: Some(campaign.targeting_rules),
}
}

pub fn apply(self, mut campaign: Campaign) -> Campaign {
if let Some(new_budget) = self.budget {
campaign.budget = new_budget;
}

if let Some(new_validators) = self.validators {
campaign.validators = new_validators;
}

// check if it was passed otherwise not sending a Title will result in clearing of the current one
if let Some(new_title) = self.title {
campaign.title = Some(new_title);
}

if let Some(new_pricing_bounds) = self.pricing_bounds {
campaign.pricing_bounds = Some(new_pricing_bounds);
}

if let Some(new_event_submission) = self.event_submission {
campaign.event_submission = Some(new_event_submission);
}

if let Some(new_ad_units) = self.ad_units {
campaign.ad_units = new_ad_units;
}

if let Some(new_targeting_rules) = self.targeting_rules {
campaign.targeting_rules = new_targeting_rules;
}

campaign
}
}
}

#[cfg(feature = "postgres")]
Expand Down
45 changes: 17 additions & 28 deletions primitives/src/sentry/accounting.rs
Original file line number Diff line number Diff line change
Expand Up @@ -68,11 +68,27 @@ impl<S: BalancesState> Balances<S> {

Ok(())
}

/// Adds the spender to the Balances with `0` if he does not exist
pub fn add_spender(&mut self, spender: Address) {
self.spenders
.entry(spender)
.or_insert_with(UnifiedNum::default);
}

/// Adds the earner to the Balances with `0` if he does not exist
pub fn add_earner(&mut self, earner: Address) {
self.earners
.entry(earner)
.or_insert_with(UnifiedNum::default);
}
}

#[derive(Debug)]
#[derive(Debug, Error)]
pub enum OverflowError {
#[error("Spender {0} amount overflowed")]
Spender(Address),
#[error("Earner {0} amount overflowed")]
Earner(Address),
}

Expand Down Expand Up @@ -196,30 +212,3 @@ mod de {
}
}
}

#[cfg(feature = "postgres")]
mod postgres {
use super::*;
use postgres_types::Json;
use tokio_postgres::Row;

impl TryFrom<&Row> for Accounting<CheckedState> {
type Error = Error;

fn try_from(row: &Row) -> Result<Self, Self::Error> {
let balances = Balances::<UncheckedState> {
earners: row.get::<_, Json<_>>("earners").0,
spenders: row.get::<_, Json<_>>("spenders").0,
state: PhantomData::default(),
}
.check()?;

Ok(Self {
channel: row.get("channel"),
balances,
updated: row.get("updated"),
created: row.get("created"),
})
}
}
}
2 changes: 1 addition & 1 deletion primitives/src/util/tests/time.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,5 +25,5 @@ pub fn past_datetime(from: Option<&DateTime<Utc>>) -> DateTime<Utc> {

let from = from.unwrap_or(&default_from);

datetime_between(&from, Some(&to))
datetime_between(from, Some(&to))
}
10 changes: 8 additions & 2 deletions primitives/src/validator.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ impl ValidatorId {
}

pub fn inner(&self) -> &[u8; 20] {
&self.0.as_bytes()
self.0.as_bytes()
}
}

Expand All @@ -39,6 +39,12 @@ impl From<&Address> for ValidatorId {
}
}

impl From<Address> for ValidatorId {
fn from(address: Address) -> Self {
Self(address)
}
}

impl From<&[u8; 20]> for ValidatorId {
fn from(bytes: &[u8; 20]) -> Self {
Self(Address::from(bytes))
Expand All @@ -47,7 +53,7 @@ impl From<&[u8; 20]> for ValidatorId {

impl AsRef<[u8]> for ValidatorId {
fn as_ref(&self) -> &[u8] {
&self.0.as_ref()
self.0.as_ref()
}
}

Expand Down
Loading