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
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
//! Bridges of a move: the order checked against the caller's own terms, then the `HyperCore`
//! payloads signed or the wallet transactions returned. The crate sends no transaction and runs
//! no move: the caller keeps the move's budget (see [`Session::sign_bridge`]).
use alloy_primitives::{Address, Bytes};
use serde::{Deserialize, Serialize};
use tracing::Instrument as _;
use super::lighter_owner;
use crate::{
Error, Result, Session,
api::{MoveRecipient, MoveRequest},
error::{ApiError, Reason},
model::{Bridge, BridgeFunding, MoveEndpoint},
protocol::{
checks::details::{self, changed, differs},
relay::{self, Checked, Expectation, Recipient},
},
transport::{Call, ops},
types::{Amount, SignatureBytes},
};
/// What a bridge must do, from the caller's own records, never from the API: its order must
/// match exactly.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct BridgeTerms {
pub(super) from: MoveEndpoint,
pub(super) to: MoveEndpoint,
pub(super) payer: Address,
pub(super) recipient: MoveRecipient,
pub(super) amount_in: Amount,
pub(super) min_out: Amount,
#[serde(default, skip_serializing_if = "Option::is_none")]
account_credit: Option<Amount>,
}
impl BridgeTerms {
/// A bridge of `amount_in` (origin base units) for the move `request`, as the caller
/// created it: its floor is its share of the move's `min_out`, rounded up; a Polymarket, GMX
/// or Aster account receives the whole output, at least the floor and the venue's minimum
/// (Polymarket: 5 pUSD). `recipient` is the move's.
pub fn for_move(
request: &MoveRequest,
recipient: MoveRecipient,
amount_in: Amount,
) -> Result<Self> {
if recipient.wire() != request.recipient {
return Err(Error::InvalidRequest("recipient is not the move's".into()));
}
let invalid = || Error::InvalidRequest("invalid bridge amount".into());
if amount_in.get().is_zero() {
return Err(invalid());
}
let floor =
relay::part_floor(amount_in.get(), request.min_out.get(), request.amount_in.get())
.ok_or_else(invalid)?;
let to = request.to.clone();
let credit = relay::is_call_venue(&to.venue)
.then(|| Amount::new(floor.max(relay::account_minimum(&to.venue))));
Ok(Self {
from: request.from.clone(),
to,
payer: request.payer,
recipient,
amount_in,
min_out: Amount::new(floor),
account_credit: credit,
})
}
/// From the payer's `token` wallet on `chain_id` instead of the move's origin.
#[must_use]
pub fn from_wallet(mut self, chain_id: u64, token: Address) -> Self {
self.from = MoveEndpoint::wallet(chain_id, token);
self
}
pub(super) fn expectation(&self) -> Expectation<'_> {
Expectation {
from: &self.from,
to: &self.to,
payer: self.payer,
recipient: match self.recipient {
MoveRecipient::Address(address) => Recipient::Address(address),
MoveRecipient::LighterAccount { index, .. } => Recipient::Lighter(index),
},
amount_in: self.amount_in.get(),
min_out: self.min_out.get(),
credit: self.account_credit.map(Amount::get),
}
}
}
/// A transaction to send: `data` to `to`, value zero.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct ContractCall {
/// The contract.
pub to: Address,
/// The calldata.
pub data: Bytes,
}
/// A wallet-origin bridge's checked transactions, from the payer's wallet.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct WalletDeposit {
/// The origin chain.
pub chain_id: u64,
/// The token deposited.
pub token: Address,
/// To send first, for exactly `amount_in`: the allowance toward the depository is below it,
/// or unknown.
pub approve: Option<ContractCall>,
/// The deposit.
pub deposit: ContractCall,
/// The payer's funds as the server read them; `None` when it cannot read the origin chain
/// (BSC): the balance is then unchecked.
pub funding: Option<BridgeFunding>,
}
#[derive(Serialize)]
struct SignaturesBody {
authorization: SignatureBytes,
send_asset: SignatureBytes,
}
impl Session {
/// Signs a `HyperCore`-origin bridge: checks its order against `terms`, signs Relay's nonce
/// mapping and the `SendAsset` to Relay's pinned depository with the session's key (the
/// payer), and submits both. Signing again signs the same payloads while the API serves the
/// bridge with the same nonce, which makes one send at most: a caller that holds that against
/// the API too keeps the nonce with the bridge's id and compares it before signing again, as
/// [`move_funds`](Self::move_funds) does in its journal.
///
/// The crate runs no move: before each bridge, the caller checks that the move's parts not
/// final without a debit (bridges not `failed` or `expired`, transfers at their take's
/// `amount_in`, withdrawals feeding the bridge) stay within the move's `amount_in`, from its
/// own records, and that the part's floor is at least its share of the move's `min_out`.
///
/// # Errors
///
/// `Verification(..)` naming the field when the order differs from `terms` or the pins, or
/// when a Lighter recipient's owner on Lighter's API is not the one `terms` names; nothing is
/// signed.
pub async fn sign_bridge(&self, bridge: &Bridge, terms: &BridgeTerms) -> Result<Bridge> {
let span = tracing::info_span!("lamarge.bridge", bridge = %bridge.id);
async {
let checked = check(self, bridge, terms).await?;
let nonce = bridge.nonce.ok_or(differs(details::NONCE))?.get();
let now_ms = self.transport().now().timestamp_millis();
let nonce = relay::check_bridge_nonce(nonce, now_ms)?;
let [authorization, send] = relay::hypercore_payloads(
checked,
&terms.expectation(),
nonce,
bridge.source_dex.as_deref(),
)?;
let body = SignaturesBody {
authorization: self.sign(&authorization).await?,
send_asset: self.sign(&send).await?,
};
let call = Call::new(&ops::SIGN_BRIDGE).segment(bridge.id).json(&body)?;
self.transport().send(call, self.auth()).await
}
.instrument(span)
.await
}
/// A wallet-origin bridge's transactions, after its order is checked against `terms` and
/// the payer's funds are read ([`Bridges::funding`](crate::api::Bridges::funding), for the
/// payer, the origin token and Relay's pinned depository): the `approve` only when the
/// allowance is below `amount_in`, then the deposit. Where the server has no reader for the
/// origin chain (BSC, `chain_unread`), the `approve` always comes and the balance is unchecked;
/// any other failure of the read is returned, to retry later. Send them yourself, fencing first with
/// [`Bridges::fence`](crate::api::Bridges::fence) and reporting each broadcast hash. The
/// caller keeps the move's budget as for [`sign_bridge`](Self::sign_bridge).
///
/// # Errors
///
/// As [`sign_bridge`](Self::sign_bridge); `Verification(Unsupported)` for a `HyperCore`
/// origin; `Verification(Changed)` while the balance is below `amount_in` (run it again once
/// the funds arrived).
pub async fn bridge_deposit(
&self,
bridge: &Bridge,
terms: &BridgeTerms,
) -> Result<WalletDeposit> {
let checked = check(self, bridge, terms).await?;
let origin = relay::relay_endpoint(&terms.from, true)?;
let deposit =
relay::bridge_transactions(checked.id, origin, terms.payer, terms.amount_in.get())
.ok_or(details::unsupported(details::BRIDGE_ORIGIN))?;
let funding = match self.bridges().funding(bridge.id).await {
Ok(funds) => Some(funds),
Err(error) if error.api().and_then(ApiError::reason) == Some(&Reason::ChainUnread) => {
None
}
Err(error) => return Err(error),
};
if let Some(funds) = &funding {
if (funds.owner, funds.token, funds.spender)
!= (terms.payer, deposit.token, relay::DEPOSITORY)
{
return Err(differs(details::BRIDGE_FUNDING).into());
}
if funds.balance < terms.amount_in {
return Err(changed(details::WALLET_FUNDS).into());
}
}
let short = funding.as_ref().is_none_or(|funds| funds.allowance < terms.amount_in);
Ok(WalletDeposit {
chain_id: deposit.chain_id,
token: deposit.token,
approve: short.then(|| ContractCall { to: deposit.token, data: deposit.approve }),
deposit: ContractCall { to: relay::DEPOSITORY, data: deposit.deposit },
funding,
})
}
}
/// The bridge's order, checked against `terms` and its own id; a Lighter recipient's owner read
/// on Lighter's API.
async fn check(session: &Session, bridge: &Bridge, terms: &BridgeTerms) -> Result<Checked> {
let now = session.transport().now().timestamp();
let checked = relay::check_bridge_order(&bridge.order.data, &terms.expectation(), now)?;
if checked.id != bridge.order.id {
return Err(differs(details::ORDER_ID).into());
}
if let MoveRecipient::LighterAccount { index, owner } = terms.recipient
&& lighter_owner(session.transport(), index).await? != Some(owner)
{
return Err(changed(details::DESTINATION_OWNER).into());
}
Ok(checked)
}
#[cfg(test)]
mod tests;