Skip to content
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

[pallet-revive] Add balance_of syscyall for fetching foreign balances #5675

Merged
merged 14 commits into from
Sep 13, 2024
Merged
14 changes: 14 additions & 0 deletions prdoc/pr_5675.prdoc
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
title: "[pallet-revive] Add balance_of syscyall for fetching foreign balances"

doc:
- audience: Runtime Dev
description: |
This adds an API method balance_of, corresponding to the BALANCE EVM opcode.

crates:
- name: pallet-revive
bump: minor
- name: pallet-revive-uapi
bump: minor
- name: pallet-revive-fixtures
bump: minor
36 changes: 36 additions & 0 deletions substrate/frame/revive/fixtures/contracts/balance_of.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
// This file is part of Substrate.

// Copyright (C) Parity Technologies (UK) Ltd.
// SPDX-License-Identifier: Apache-2.0

// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#![no_std]
#![no_main]

use common::{input, u64_output};
use uapi::{HostFn, HostFnImpl as api};

#[no_mangle]
#[polkavm_derive::polkavm_export]
pub extern "C" fn deploy() {}

#[no_mangle]
#[polkavm_derive::polkavm_export]
pub extern "C" fn call() {
input!(address: &[u8; 20],);

let reported_free_balance = u64_output!(api::balance_of, address);

assert_ne!(reported_free_balance, 0);
}
20 changes: 20 additions & 0 deletions substrate/frame/revive/src/benchmarking/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -612,6 +612,26 @@ mod benchmarks {
assert_eq!(U256::from_little_endian(&memory[..]), runtime.ext().balance());
}

#[benchmark(pov_mode = Measured)]
fn seal_balance_of() {
let len = <sp_core::U256 as MaxEncodedLen>::max_encoded_len();
let account = account::<T::AccountId>("target", 0, 0);
let address = T::AddressMapper::to_address(&account);
let balance = Pallet::<T>::min_balance() * 2u32.into();
T::Currency::set_balance(&account, balance);

build_runtime!(runtime, memory: [vec![0u8; len], address.0, ]);

let result;
#[block]
{
result = runtime.bench_balance_of(memory.as_mut_slice(), len as u32, 0);
}

assert_ok!(result);
assert_eq!(U256::from_little_endian(&memory[..len]), runtime.ext().balance_of(&address));
}

#[benchmark(pov_mode = Measured)]
fn seal_value_transferred() {
build_runtime!(runtime, memory: [[0u8;32], ]);
Expand Down
23 changes: 17 additions & 6 deletions substrate/frame/revive/src/exec.rs
Original file line number Diff line number Diff line change
Expand Up @@ -295,6 +295,9 @@ pub trait Ext: sealing::Sealed {
/// Returns a reference to the account id of the current contract.
fn account_id(&self) -> &AccountIdOf<Self::T>;

/// Returns the balance of an AccountId
fn account_balance(&self, who: &AccountIdOf<Self::T>) -> U256;

athei marked this conversation as resolved.
Show resolved Hide resolved
/// Returns a reference to the [`H160`] address of the current contract.
fn address(&self) -> H160 {
<Self::T as Config>::AddressMapper::to_address(self.account_id())
Expand All @@ -305,6 +308,11 @@ pub trait Ext: sealing::Sealed {
/// The `value_transferred` is already added.
fn balance(&self) -> U256;

/// Returns the balance of the supplied account.
///
/// The `value_transferred` is already added.
fn balance_of(&self, address: &H160) -> U256;

/// Returns the value transferred along with this call.
fn value_transferred(&self) -> U256;

Expand Down Expand Up @@ -1463,6 +1471,10 @@ where
&self.top_frame().account_id
}

fn account_balance(&self, who: &AccountIdOf<Self::T>) -> U256 {
T::Currency::reducible_balance(who, Preservation::Preserve, Fortitude::Polite).into()
}

fn caller(&self) -> Origin<T> {
if let Some(caller) = &self.top_frame().delegate_caller {
caller.clone()
Expand Down Expand Up @@ -1496,12 +1508,11 @@ where
}

fn balance(&self) -> U256 {
T::Currency::reducible_balance(
&self.top_frame().account_id,
Preservation::Preserve,
Fortitude::Polite,
)
.into()
self.account_balance(&self.top_frame().account_id)
}

fn balance_of(&self, address: &H160) -> U256 {
self.account_balance(&<Self::T as Config>::AddressMapper::to_account_id(address))
}

fn value_transferred(&self) -> U256 {
Expand Down
25 changes: 25 additions & 0 deletions substrate/frame/revive/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4063,6 +4063,31 @@ mod run_tests {
});
}

#[test]
fn balance_of_api() {
let (wasm, _code_hash) = compile_module("balance_of").unwrap();
ExtBuilder::default().existential_deposit(200).build().execute_with(|| {
let _ = Balances::set_balance(&ALICE, 1_000_000);
let _ = Balances::set_balance(&ETH_ALICE, 1_000_000);

let Contract { addr, .. } =
builder::bare_instantiate(Code::Upload(wasm.to_vec())).build_and_unwrap_contract();

// The fixture asserts a non-zero returned free balance of the account;
// The ETH_ALICE account is endowed;
// Hence we should not revert
assert_ok!(builder::call(addr).data(ALICE_ADDR.0.to_vec()).build());

// The fixture asserts a non-zero returned free balance of the account;
// The ETH_BOB account is not endowed;
// Hence we should revert
assert_err_ignore_postinfo!(
builder::call(addr).data(BOB_ADDR.0.to_vec()).build(),
<Error<Test>>::ContractTrapped
);
});
}

#[test]
fn balance_api_returns_free_balance() {
let (wasm, _code_hash) = compile_module("balance").unwrap();
Expand Down
24 changes: 24 additions & 0 deletions substrate/frame/revive/src/wasm/runtime.rs
Original file line number Diff line number Diff line change
Expand Up @@ -314,6 +314,8 @@ pub enum RuntimeCosts {
GasLeft,
/// Weight of calling `seal_balance`.
Balance,
/// Weight of calling `seal_balance_of`.
BalanceOf,
/// Weight of calling `seal_value_transferred`.
ValueTransferred,
/// Weight of calling `seal_minimum_balance`.
Expand Down Expand Up @@ -457,6 +459,7 @@ impl<T: Config> Token<T> for RuntimeCosts {
Address => T::WeightInfo::seal_address(),
GasLeft => T::WeightInfo::seal_gas_left(),
Balance => T::WeightInfo::seal_balance(),
BalanceOf => T::WeightInfo::seal_balance_of(),
ValueTransferred => T::WeightInfo::seal_value_transferred(),
MinimumBalance => T::WeightInfo::seal_minimum_balance(),
BlockNumber => T::WeightInfo::seal_block_number(),
Expand Down Expand Up @@ -1515,6 +1518,27 @@ pub mod env {
)?)
}

/// Stores the *free* balance of the supplied address into the supplied buffer.
/// See [`pallet_revive_uapi::HostFn::balance`].
#[api_version(0)]
fn balance_of(
&mut self,
memory: &mut M,
addr_ptr: u32,
out_ptr: u32,
) -> Result<(), TrapReason> {
self.charge_gas(RuntimeCosts::BalanceOf)?;
let mut address = H160::zero();
memory.read_into_buf(addr_ptr, address.as_bytes_mut())?;
Ok(self.write_fixed_sandbox_output(
memory,
out_ptr,
&as_bytes(self.ext.balance_of(&address)),
false,
already_charged,
)?)
}

/// Stores the value transferred along with this call/instantiate into the supplied buffer.
/// See [`pallet_revive_uapi::HostFn::value_transferred`].
#[api_version(0)]
Expand Down
Loading
Loading