1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
use serde::{Deserialize, Serialize};
use std::fmt;
use crate::{config::TokenInfo, util::ApiUrl, Address, Campaign, Channel};
use parse_display::{Display, FromStr};
#[derive(Serialize, Deserialize, Hash, Clone, Copy, Eq, PartialEq, Display, FromStr)]
#[serde(transparent)]
pub struct ChainId(u32);
impl ChainId {
pub fn new(id: u32) -> Self {
assert!(id != 0);
Self(id)
}
pub fn to_u32(self) -> u32 {
self.0
}
}
impl From<u32> for ChainId {
fn from(id: u32) -> Self {
Self::new(id)
}
}
impl fmt::Debug for ChainId {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "ChainId({})", self.0)
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Hash)]
pub struct Chain {
pub chain_id: ChainId,
pub rpc: ApiUrl,
pub outpace: Address,
}
#[derive(Debug, Deserialize, Serialize, PartialEq, Eq, Hash, Clone)]
pub struct ChainOf<T = ()> {
pub context: T,
pub chain: Chain,
pub token: TokenInfo,
}
impl<T> ChainOf<T> {
pub fn with<C>(self, context: C) -> ChainOf<C> {
ChainOf {
context,
chain: self.chain,
token: self.token,
}
}
}
impl ChainOf<()> {
pub fn new(chain: Chain, token: TokenInfo) -> ChainOf<()> {
ChainOf {
context: (),
chain,
token,
}
}
pub fn with_channel(self, channel: Channel) -> ChainOf<Channel> {
ChainOf {
context: channel,
chain: self.chain,
token: self.token,
}
}
pub fn with_campaign(self, campaign: Campaign) -> ChainOf<Campaign> {
ChainOf {
context: campaign,
chain: self.chain,
token: self.token,
}
}
}
impl ChainOf<Campaign> {
pub fn of_channel(&self) -> ChainOf<Channel> {
ChainOf {
context: self.context.channel,
token: self.token.clone(),
chain: self.chain.clone(),
}
}
}
#[cfg(feature = "postgres")]
mod postgres {
use super::ChainId;
use bytes::BytesMut;
use std::error::Error;
use tokio_postgres::types::{accepts, to_sql_checked, FromSql, IsNull, ToSql, Type};
impl<'a> FromSql<'a> for ChainId {
fn from_sql(ty: &Type, raw: &'a [u8]) -> Result<ChainId, Box<dyn Error + Sync + Send>> {
let value = <i32 as FromSql>::from_sql(ty, raw)?;
Ok(ChainId(u32::try_from(value)?))
}
accepts!(INT4);
}
impl ToSql for ChainId {
fn to_sql(
&self,
ty: &Type,
w: &mut BytesMut,
) -> Result<IsNull, Box<dyn Error + Sync + Send>> {
<i32 as ToSql>::to_sql(&self.0.try_into()?, ty, w)
}
accepts!(INT4);
to_sql_checked!();
}
}