-
Notifications
You must be signed in to change notification settings - Fork 2
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
[FIL-227] Automatic allocator (#225)
--------- Co-authored-by: Filip Lelek <[email protected]>
- Loading branch information
1 parent
f3a74f1
commit d7ac445
Showing
19 changed files
with
1,186 additions
and
841 deletions.
There are no files selected for viewing
Large diffs are not rendered by default.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,57 @@ | ||
use crate::get_database_connection; | ||
use crate::models::autoallocations::AddressWrapper; | ||
use crate::models::autoallocations::{ | ||
Column, Entity as Autoallocations, Model as AutoallocationModel, | ||
}; | ||
use alloy::primitives::Address; | ||
use chrono::{DateTime, FixedOffset}; | ||
use sea_orm::{entity::*, query::*, DbBackend, DbErr}; | ||
|
||
pub async fn get_last_client_autoallocation( | ||
client_evm_address: impl Into<AddressWrapper>, | ||
) -> Result<Option<DateTime<FixedOffset>>, DbErr> { | ||
let response = get_autoallocation(client_evm_address.into()).await?; | ||
Ok(response.map(|allocation| allocation.last_allocation)) | ||
} | ||
|
||
pub async fn create_or_update_autoallocation( | ||
client_evm_address: &Address, | ||
days_to_next_autoallocation: &i64, | ||
) -> Result<u64, sea_orm::DbErr> { | ||
let conn = get_database_connection().await?; | ||
let client_address = client_evm_address.to_checksum(None); | ||
|
||
let exec_res = conn | ||
.execute(Statement::from_sql_and_values( | ||
DbBackend::Postgres, | ||
"INSERT INTO autoallocations (evm_wallet_address, last_allocation) | ||
VALUES ($1, NOW()) | ||
ON CONFLICT (evm_wallet_address) | ||
DO UPDATE SET last_allocation = NOW() | ||
WHERE autoallocations.last_allocation <= NOW() - (INTERVAL '1 day' * $2::int);", | ||
[client_address.into(), (*days_to_next_autoallocation).into()], | ||
)) | ||
.await?; | ||
Ok(exec_res.rows_affected()) | ||
} | ||
|
||
pub async fn get_autoallocation( | ||
client_evm_address: impl Into<AddressWrapper>, | ||
) -> Result<Option<AutoallocationModel>, DbErr> { | ||
let conn = get_database_connection().await?; | ||
let response = Autoallocations::find() | ||
.filter(Column::EvmWalletAddress.contains(client_evm_address.into())) | ||
.one(&conn) | ||
.await?; | ||
Ok(response) | ||
} | ||
|
||
pub async fn delete_autoallocation( | ||
client_evm_address: impl Into<AddressWrapper>, | ||
) -> Result<(), sea_orm::DbErr> { | ||
let conn = get_database_connection().await?; | ||
Autoallocations::delete_by_id(client_evm_address.into()) | ||
.exec(&conn) | ||
.await?; | ||
Ok(()) | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,3 +1,4 @@ | ||
pub mod allocation_amounts; | ||
pub mod allocators; | ||
pub mod applications; | ||
pub mod autoallocations; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,41 @@ | ||
use alloy::primitives::{Address, AddressError}; | ||
use chrono::{DateTime, FixedOffset}; | ||
use sea_orm::entity::prelude::*; | ||
use sea_orm_newtype::DeriveNewType; | ||
use serde::{Deserialize, Serialize}; | ||
|
||
#[derive(Clone, Debug, PartialEq, DeriveEntityModel, Eq, Serialize, Deserialize)] | ||
#[sea_orm(table_name = "autoallocations")] | ||
pub struct Model { | ||
#[sea_orm(primary_key, auto_increment = false)] | ||
pub evm_wallet_address: AddressWrapper, | ||
pub last_allocation: DateTime<FixedOffset>, | ||
} | ||
|
||
#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)] | ||
pub enum Relation {} | ||
|
||
impl ActiveModelBehavior for ActiveModel {} | ||
|
||
#[derive(Clone, Debug, PartialEq, DeriveNewType, Eq, Serialize, Deserialize)] | ||
#[sea_orm_newtype(try_from_into = "String", primary_key)] | ||
pub struct AddressWrapper(pub Address); | ||
|
||
impl TryFrom<String> for AddressWrapper { | ||
type Error = AddressError; | ||
fn try_from(value: String) -> Result<Self, Self::Error> { | ||
Ok(AddressWrapper(Address::parse_checksummed(value, None)?)) | ||
} | ||
} | ||
|
||
impl From<AddressWrapper> for String { | ||
fn from(value: AddressWrapper) -> Self { | ||
value.0.to_checksum(None) | ||
} | ||
} | ||
|
||
impl From<Address> for AddressWrapper { | ||
fn from(value: Address) -> Self { | ||
AddressWrapper(value) | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -5,3 +5,4 @@ pub mod prelude; | |
pub mod allocation_amounts; | ||
pub mod allocators; | ||
pub mod applications; | ||
pub mod autoallocations; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,23 @@ | ||
use actix_web::{get, post, web, HttpResponse, Responder}; | ||
use fplus_database::database::autoallocations as autoallocations_db; | ||
use fplus_lib::core::autoallocator; | ||
use fplus_lib::core::{LastAutoallocationQueryParams, TriggerAutoallocationInfo}; | ||
#[get("/autoallocator/last_client_allocation")] | ||
pub async fn last_client_allocation( | ||
query: web::Query<LastAutoallocationQueryParams>, | ||
) -> impl Responder { | ||
match autoallocations_db::get_last_client_autoallocation(query.evm_wallet_address).await { | ||
Ok(last_client_allocation) => { | ||
HttpResponse::Ok().body(serde_json::to_string_pretty(&last_client_allocation).unwrap()) | ||
} | ||
Err(e) => HttpResponse::BadRequest().body(e.to_string()), | ||
} | ||
} | ||
|
||
#[post("autoallocator/trigger_autoallocation")] | ||
pub async fn trigger_autoallocation(info: web::Json<TriggerAutoallocationInfo>) -> impl Responder { | ||
match autoallocator::trigger_autoallocation(&info.into_inner()).await { | ||
Ok(()) => HttpResponse::Ok().body(serde_json::to_string_pretty("Success").unwrap()), | ||
Err(e) => HttpResponse::BadRequest().body(e.to_string()), | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
83 changes: 83 additions & 0 deletions
83
fplus-lib/src/core/autoallocator/metaallocator_interaction.rs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,83 @@ | ||
use std::str::FromStr; | ||
|
||
use crate::config::get_env_var_or_default; | ||
use crate::error::LDNError; | ||
use alloy::{ | ||
network::{EthereumWallet, TransactionBuilder}, | ||
primitives::{Address, Bytes, U256}, | ||
providers::{Provider, ProviderBuilder}, | ||
rpc::types::eth::TransactionRequest, | ||
signers::local::PrivateKeySigner, | ||
sol, | ||
sol_types::SolCall, | ||
}; | ||
use anyhow::Result; | ||
use fplus_database::config::get_env_or_throw; | ||
use fvm_shared::address::{set_current_network, Address as FilecoinAddress, Network}; | ||
sol! { | ||
#[allow(missing_docs)] | ||
function addVerifiedClient(bytes calldata clientAddress, uint256 amount); | ||
} | ||
|
||
async fn get_provider() -> Result<impl Provider, LDNError> { | ||
let private_key = get_env_or_throw("AUTOALLOCATOR_PRIVATE_KEY"); | ||
let signer: PrivateKeySigner = private_key.parse().expect("Should parse private key"); | ||
let wallet = EthereumWallet::from(signer); | ||
let rpc_url = get_env_var_or_default("GLIF_NODE_URL"); | ||
let provider = ProviderBuilder::new() | ||
.with_recommended_fillers() | ||
.wallet(wallet) | ||
.on_builtin(&rpc_url) | ||
.await | ||
.map_err(|e| LDNError::New(format!("Building provider failed: {}", e)))?; | ||
Ok(provider) | ||
} | ||
|
||
pub async fn add_verified_client(address: &str, amount: &u64) -> Result<(), LDNError> { | ||
let provider = get_provider().await?; | ||
let fil_address = decode_filecoin_address(address)?; | ||
let amount = U256::try_from(*amount) | ||
.map_err(|e| LDNError::New(format!("Failed to prase amount to U256 /// {}", e)))?; | ||
let call = addVerifiedClientCall { | ||
clientAddress: fil_address.into(), | ||
amount, | ||
} | ||
.abi_encode(); | ||
let allocator_contract = | ||
Address::parse_checksummed(get_env_var_or_default("ALLOCATOR_CONTRACT_ADDRESS"), None) | ||
.map_err(|e| { | ||
LDNError::New(format!( | ||
"Parse ALLOCATOR_CONTRACT_ADDRESS to Address failed: {}", | ||
e | ||
)) | ||
})?; | ||
let input = Bytes::from(call); | ||
|
||
let tx = TransactionRequest::default() | ||
.with_to(allocator_contract) | ||
.with_input(input) | ||
.with_gas_limit(45_000_000); | ||
|
||
provider | ||
.send_transaction(tx) | ||
.await | ||
.map_err(|e| LDNError::New(format!("RPC error: {}", e)))? | ||
.watch() | ||
.await | ||
.map_err(|e| LDNError::New(format!("Transaction failed: {}", e)))?; | ||
Ok(()) | ||
} | ||
|
||
fn decode_filecoin_address(address: &str) -> Result<Vec<u8>, LDNError> { | ||
let address_prefix = address.get(0..1); | ||
if let Some(address_prefix) = address_prefix { | ||
if address_prefix.eq("f") { | ||
set_current_network(Network::Mainnet); | ||
} else if address_prefix.eq("t") { | ||
set_current_network(Network::Testnet); | ||
} | ||
} | ||
let fil_address = FilecoinAddress::from_str(address) | ||
.map_err(|e| LDNError::New(format!("Failed to prase address from string /// {}", e)))?; | ||
Ok(fil_address.to_bytes()) | ||
} |
Oops, something went wrong.