Skip to content

Commit

Permalink
feat: add api to get ft balances for multiple accounts (#905)
Browse files Browse the repository at this point in the history
<!--
Thanks for submitting a pull request! Here are some helpful tips:

* Always create branches on and target the `develop` branch.
* Run all the tests locally and ensure that they are passing.
* Run `make format` to ensure that the code is formatted.
* Run `make check` to ensure that all checks passed successfully.
* Small commits and contributions that attempt one single goal is
preferable.
* If the idea changes or adds anything functional which will affect
users, an
AIP discussion is required first on the Aurora forum: 

https://forum.aurora.dev/discussions/AIPs%20(Aurora%20Improvement%20Proposals).
* Avoid breaking the public API (namely in engine/src/lib.rs) unless
required.
* If your PR is a WIP, ensure that you enable "draft" mode.
* Your first PRs won't use the CI automatically unless a maintainer
starts.
If this is not your first PR, please do NOT abuse the CI resources.

Checklist:
- [ ] I have performed a self-review of my code
- [ ] I have documented my code, particularly in the hard-to-understand
areas
- [ ] I have made corresponding changes to the documentation
- [ ] I have added tests to prove my fix or new feature is effective and
works
- [ ] Any dependent changes have been merged
- [ ] The PR is targeting the `develop` branch and not `master`
- [ ] I have pre-squashed my commits into a single commit and rebased.
-->

## Description
The PR adds a public method to the engine/internal connector to get
balances of multiple accounts. This is needed because we have changed
the migration logic to migrate the balances based on the on-chain data,
not off-chain.
<!-- 
Provide a general summary of your changes. A clear overview along with
an
in-depth explanation is beneficial.

If this PR closes any issues, be sure to add "closes #<number>"
somewhere.
-->

## Performance / NEAR gas cost considerations
The borsh is used instead of JSON to decrease gas usage and migrate more
accounts in one batch.
<!--
Performance regressions are not ideal, though we welcome performance 
improvements. Any PR must be completely mindful of any gas cost
increases. The
CI will fail if the gas costs change at all. Do update these tests to 
accommodate for the new gas changes. It is good to explain 
this change, if necessary.
-->

## Testing
Added a test to the crate `aurora-engine-tests`, not
`aurora-engine-tests-connector` because the second one is enabled just
for silo builds.
<!--
Please describe the tests that you ran to verify your changes.
-->

## How should this be reviewed

<!--
Include any recommendations of areas to be careful of to ensure that the
reviewers use extra attention.
-->

## Additional information
It's controversial whether to use `HashMap<AccountId, Balance>` or
`Vec<(AccountId, Balance)>`; the `HashMap` prevents duplication, but on
the other side, it increases gas usage.
<!--
Include any additional information which you think should be in this PR,
such
as prior arts, future extensions, unresolved problems, or a TODO list
which
should be followed up.
-->

---------

Co-authored-by: Oleksandr Anyshchenko <oleksandr.anyshchenko@aurora.dev>
Co-authored-by: Michael Birch <michael.birch@aurora.dev>
  • Loading branch information
3 people committed Mar 27, 2024
1 parent 9e6d122 commit 174a6c6
Show file tree
Hide file tree
Showing 6 changed files with 90 additions and 8 deletions.
51 changes: 47 additions & 4 deletions engine-tests/src/tests/erc20_connector.rs
Original file line number Diff line number Diff line change
Expand Up @@ -393,7 +393,6 @@ pub mod workspace {
nep_141_balance_of, transfer_nep_141, transfer_nep_141_to_erc_20,
};
use aurora_engine::parameters::{CallArgs, FunctionCallArgsV2};
#[cfg(feature = "ext-connector")]
use aurora_engine::proof::Proof;
use aurora_engine_types::parameters::engine::TransactionStatus;
use aurora_engine_workspace::account::Account;
Expand All @@ -407,6 +406,9 @@ pub mod workspace {
const FT_ACCOUNT: &str = "test_token";
const INITIAL_ETH_BALANCE: u64 = 777_777_777;
const ETH_EXIT_AMOUNT: u64 = 111_111_111;
const ETH_CUSTODIAN_ADDRESS: &str = "096de9c2b8a5b8c22cee3289b101f6960d68e51e";
#[cfg(not(feature = "ext-connector"))]
const ONE_YOCTO: NearToken = NearToken::from_yoctonear(1);

#[tokio::test]
async fn test_ghsa_5c82_x4m4_hcj6_exploit() {
Expand Down Expand Up @@ -769,6 +771,49 @@ pub mod workspace {
);
}

#[cfg(not(feature = "ext-connector"))]
#[tokio::test]
async fn test_ft_balances_of() {
use aurora_engine::parameters::FungibleTokenMetadata;
use aurora_engine_types::account_id::AccountId;
use aurora_engine_types::HashMap;

let aurora = deploy_engine().await;
let metadata = FungibleTokenMetadata::default();
aurora
.set_eth_connector_contract_data(
aurora.id(),
ETH_CUSTODIAN_ADDRESS.to_string(),
metadata,
)
.transact()
.await
.unwrap();

deposit_balance(&aurora).await;

let balances: HashMap<AccountId, u128> = HashMap::from([
(AccountId::new("account1").unwrap(), 10),
(AccountId::new("account2").unwrap(), 20),
(AccountId::new("account3").unwrap(), 30),
]);

for (account_id, amount) in &balances {
aurora
.ft_transfer(account_id, (*amount).into(), None)
.deposit(ONE_YOCTO)
.transact()
.await
.unwrap();
let blanace = aurora.ft_balance_of(account_id).await.unwrap().result;
assert_eq!(blanace.0, *amount);
}

let accounts = balances.keys().cloned().collect();
let result = aurora.ft_balances_of(&accounts).await.unwrap().result;
assert_eq!(result, balances);
}

async fn test_exit_to_near_eth_common() -> anyhow::Result<TestExitToNearEthContext> {
let aurora = deploy_engine().await;
let chain_id = aurora.get_chain_id().await?.result.as_u64();
Expand Down Expand Up @@ -974,12 +1019,11 @@ pub mod workspace {
}
}

#[cfg(feature = "ext-connector")]
async fn deposit_balance(aurora: &EngineContract) {
let proof = create_test_proof(
INITIAL_ETH_BALANCE,
aurora.id().as_ref(),
"096de9c2b8a5b8c22cee3289b101f6960d68e51e",
ETH_CUSTODIAN_ADDRESS,
);
let result = aurora.deposit(proof).max_gas().transact().await.unwrap();
assert!(result.is_success());
Expand All @@ -1003,7 +1047,6 @@ pub mod workspace {
aurora: EngineContract,
}

#[cfg(feature = "ext-connector")]
fn create_test_proof(
deposit_amount: u64,
recipient_id: &str,
Expand Down
6 changes: 5 additions & 1 deletion engine-workspace/src/contract.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ use crate::operation::{
CallStageUpgrade, CallStateMigration, CallStorageDeposit, CallStorageUnregister,
CallStorageWithdraw, CallSubmit, CallUpgrade, CallWithdraw, ViewAccountsCounter, ViewBalance,
ViewBlockHash, ViewBridgeProver, ViewChainId, ViewCode, ViewErc20FromNep141,
ViewFactoryWnearAddress, ViewFtBalanceOf, ViewFtBalanceOfEth, ViewFtMetadata,
ViewFactoryWnearAddress, ViewFtBalanceOf, ViewFtBalanceOfEth, ViewFtBalancesOf, ViewFtMetadata,
ViewFtTotalEthSupplyOnAurora, ViewFtTotalEthSupplyOnNear, ViewFtTotalSupply,
ViewGetErc20Metadata, ViewGetEthConnectorContractAccount, ViewGetFixedGas, ViewGetSiloParams,
ViewGetWhitelistStatus, ViewIsUsedProof, ViewNep141FromErc20, ViewNonce, ViewOwner,
Expand Down Expand Up @@ -377,6 +377,10 @@ impl EngineContract {
ViewFtBalanceOf::view(&self.contract).args_json(json!({ "account_id": account_id }))
}

pub fn ft_balances_of(&self, accounts: &Vec<AccountId>) -> ViewFtBalancesOf {
ViewFtBalancesOf::view(&self.contract).args_borsh(accounts)
}

pub fn storage_balance_of(&self, account_id: &AccountId) -> ViewStorageBalanceOf {
ViewStorageBalanceOf::view(&self.contract).args_json(json!({ "account_id": account_id }))
}
Expand Down
5 changes: 4 additions & 1 deletion engine-workspace/src/operation.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ use aurora_engine_types::parameters::connector::{
use aurora_engine_types::parameters::engine::{StorageBalance, SubmitResult, TransactionStatus};
use aurora_engine_types::parameters::silo::{FixedGasArgs, SiloParamsArgs, WhitelistStatusArgs};
use aurora_engine_types::types::Address;
use aurora_engine_types::{H256, U256};
use aurora_engine_types::{HashMap, H256, U256};
use near_sdk::json_types::U128;
use near_sdk::PromiseOrValue;

Expand Down Expand Up @@ -77,6 +77,7 @@ impl_call_return![
impl_view_return![
(ViewFtTotalSupply => U128, View::FtTotalSupply, json),
(ViewFtBalanceOf => U128, View::FtBalanceOf, json),
(ViewFtBalancesOf => HashMap<AccountId, u128>, View::FtBalancesOf, borsh),
(ViewStorageBalanceOf => StorageBalance, View::StorageBalanceOf, json),
(ViewFtMetadata => FungibleTokenMetadata, View::FtMetadata, json),
(ViewVersion => String, View::Version, borsh),
Expand Down Expand Up @@ -226,6 +227,7 @@ pub enum View {
IsUsedProof,
FtTotalSupply,
FtBalanceOf,
FtBalancesOf,
FtBalanceOfEth,
FtTotalEthSupplyOnAurora,
FtTotalEthSupplyOnNear,
Expand Down Expand Up @@ -261,6 +263,7 @@ impl AsRef<str> for View {
View::IsUsedProof => "is_used_proof",
View::FtTotalSupply => "ft_total_supply",
View::FtBalanceOf => "ft_balance_of",
View::FtBalancesOf => "ft_balances_of",
View::FtBalanceOfEth => "ft_balance_of_eth",
View::FtTotalEthSupplyOnAurora => "ft_total_eth_supply_on_aurora",
View::FtTotalEthSupplyOnNear => "ft_total_eth_supply_on_near",
Expand Down
17 changes: 17 additions & 0 deletions engine/src/contract_methods/connector/internal.rs
Original file line number Diff line number Diff line change
Expand Up @@ -377,6 +377,13 @@ pub fn ft_balance_of<I: IO + Copy>(io: I) -> Result<(), ContractError> {
Ok(())
}

#[cfg(not(feature = "ext-connector"))]
pub fn ft_balances_of<I: IO + Copy>(io: I) -> Result<(), ContractError> {
let accounts: Vec<AccountId> = io.read_input_borsh()?;
EthConnectorContract::init(io)?.ft_balances_of(accounts);
Ok(())
}

#[named]
pub fn finish_deposit<I: IO + Copy, E: Env, H: PromiseHandler>(
io: I,
Expand Down Expand Up @@ -818,6 +825,16 @@ impl<I: IO + Copy> EthConnectorContract<I> {
self.io.return_output(format!("\"{balance}\"").as_bytes());
}

/// Return `nETH` balances for accounts (ETH on NEAR).
pub fn ft_balances_of(&mut self, accounts: Vec<AccountId>) {
let mut balances = aurora_engine_types::HashMap::new();
for account_id in accounts {
let balance = self.ft.ft_balance_of(&account_id);
balances.insert(account_id, balance);
}
self.io.return_output(&borsh::to_vec(&balances).unwrap());
}

/// Return `ETH` balance (ETH on Aurora).
pub fn ft_balance_of_eth_on_aurora(
&mut self,
Expand Down
6 changes: 6 additions & 0 deletions engine/src/contract_methods/connector/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -346,6 +346,12 @@ pub fn ft_balance_of<I: IO + Copy + PromiseHandler>(io: I) -> Result<(), Contrac
Ok(())
}

#[cfg(not(feature = "ext-connector"))]
pub fn ft_balances_of<I: IO + Copy + PromiseHandler>(io: I) -> Result<(), ContractError> {
internal::ft_balances_of(io)?;
Ok(())
}

pub fn ft_balance_of_eth<I: IO + Copy>(io: I) -> Result<(), ContractError> {
let args = io.read_input_borsh()?;
EthConnectorContract::init(io)?.ft_balance_of_eth_on_aurora(&args)?;
Expand Down
13 changes: 11 additions & 2 deletions engine/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -252,8 +252,8 @@ mod contract {
.sdk_unwrap();
}

/// Returns an unsigned integer where each 1-bit means that a precompile corresponding to that bit is paused and
/// 0-bit means not paused.
/// Returns an unsigned integer where each bit set to 1 means that corresponding precompile
/// to that bit is paused and 0-bit means not paused.
#[no_mangle]
pub extern "C" fn paused_precompiles() {
let io = Runtime;
Expand Down Expand Up @@ -653,6 +653,15 @@ mod contract {
.sdk_unwrap();
}

#[no_mangle]
#[cfg(not(feature = "ext-connector"))]
pub extern "C" fn ft_balances_of() {
let io = Runtime;
contract_methods::connector::ft_balances_of(io)
.map_err(ContractError::msg)
.sdk_unwrap();
}

#[no_mangle]
pub extern "C" fn ft_balance_of_eth() {
let io = Runtime;
Expand Down

0 comments on commit 174a6c6

Please sign in to comment.