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

feat!: bank precompile #2860

Open
wants to merge 34 commits into
base: develop
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 22 commits
Commits
Show all changes
34 commits
Select commit Hold shift + click to select a range
d06485f
feat: bank precompile
fbac Sep 10, 2024
969d2d2
feat: add deposit
fbac Sep 11, 2024
71aa8d5
feat: extend deposit
fbac Sep 11, 2024
322618b
PoC: spend amount on behalf of EOA
fbac Sep 11, 2024
7e85925
feat: expand deposit with transferFrom
fbac Sep 11, 2024
5fe30cf
use CallEVM instead on ZRC20 bindings
fbac Sep 11, 2024
f69c695
divide the contract into different files
fbac Sep 11, 2024
5863536
initialize e2e testing
fbac Sep 11, 2024
12a5138
remove duplicated funding
fbac Sep 11, 2024
a4be05e
add codecov
fbac Sep 11, 2024
75efde6
expand e2e
fbac Sep 11, 2024
6340abb
fix: wait for deposit tx to be mined
fbac Sep 11, 2024
0f347f2
apply first round of reviews
fbac Sep 12, 2024
e0fa24a
cover al error types test
fbac Sep 12, 2024
cf17671
fixes using time.Since
fbac Sep 12, 2024
02ddce3
Include CallContract interface
fbac Sep 12, 2024
c1836a3
fix eth events in deposit precompile method
skosito Sep 16, 2024
8503dc8
emit Deposit event
fbac Sep 16, 2024
6a19fb0
add withdraw function
fbac Sep 17, 2024
e7ddcb0
finalize withdraw
fbac Sep 17, 2024
f1e5b3a
pack event arguments generically
fbac Sep 17, 2024
05d0bfb
add high level event function
fbac Sep 17, 2024
0fa8d50
first round of review fixes
fbac Sep 17, 2024
b6b78a9
second round of reviews
fbac Sep 18, 2024
6271e7a
create bank account when instantiating bank
fbac Sep 18, 2024
1a4f553
e2e: add good and bad scenarios
fbac Sep 19, 2024
6caabef
Merge branch 'develop' into feat/bank-precompile
fbac Sep 19, 2024
9ed6bfb
modify fmt
fbac Sep 19, 2024
b8094e2
chore: group input into eventData struct
fbac Sep 19, 2024
a7533eb
docs: document bank's methods
fbac Sep 19, 2024
67ad4fa
chore: generate files with suffix .gen.go
fbac Sep 20, 2024
82f5204
chore: assert errors with errorIs
fbac Sep 20, 2024
4d0a57b
chore: reset e2e test by resetting allowance
fbac Sep 20, 2024
c9bf427
test: add first batch of unit test
fbac Sep 21, 2024
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions Dockerfile-localnet
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ EXPOSE 22
FROM base-runtime AS latest-runtime

COPY --from=cosmovisor-build /go/bin/cosmovisor /usr/local/bin
COPY --from=latest-build /go/bin/zetacored /go/bin/zetaclientd /go/bin/zetaclientd-supervisor /go/bin/zetae2e /usr/local/bin
COPY --from=latest-build /go/bin/zetacored /go/bin/zetaclientd /go/bin/zetaclientd-supervisor /go/bin/zetae2e /usr/local/bin/
fbac marked this conversation as resolved.
Show resolved Hide resolved

# Optional old version build (from source). This old build is used as the genesis version in the upgrade tests.
# Use --target latest-runtime to skip.
Expand All @@ -75,7 +75,7 @@ RUN cd node && make install
FROM base-runtime AS old-runtime-source

COPY --from=cosmovisor-build /go/bin/cosmovisor /usr/local/bin
COPY --from=old-build-source /go/bin/zetacored /go/bin/zetaclientd /usr/local/bin
COPY --from=old-build-source /go/bin/zetacored /go/bin/zetaclientd /usr/local/bin/
COPY --from=latest-build /go/bin/zetaclientd-supervisor /usr/local/bin

# Optional old version build (from binary).
Expand Down
7 changes: 7 additions & 0 deletions app/app.go
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,7 @@ import (
"github.com/zeta-chain/node/docs/openapi"
zetamempool "github.com/zeta-chain/node/pkg/mempool"
"github.com/zeta-chain/node/precompiles"
bankprecompile "github.com/zeta-chain/node/precompiles/bank"
srvflags "github.com/zeta-chain/node/server/flags"
authoritymodule "github.com/zeta-chain/node/x/authority"
authoritykeeper "github.com/zeta-chain/node/x/authority/keeper"
Expand Down Expand Up @@ -570,6 +571,7 @@ func New(
precompiles.StatefulContracts(
&app.FungibleKeeper,
app.StakingKeeper,
app.BankKeeper,
appCodec,
storetypes.TransientGasConfig(),
),
Expand Down Expand Up @@ -1064,6 +1066,11 @@ func (app *App) BlockedAddrs() map[string]bool {
// Each enabled precompiled stateful contract should be added as a BlockedAddrs.
// That way it's marked as non payable by the bank keeper.
for addr, enabled := range precompiles.EnabledStatefulContracts {
// bank precompile has to be able to receive funds.
fbac marked this conversation as resolved.
Show resolved Hide resolved
if addr == bankprecompile.ContractAddress {
continue
}

if enabled {
blockList[addr.String()] = enabled
}
Expand Down
1 change: 1 addition & 0 deletions changelog.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
* [2784](https://github.com/zeta-chain/node/pull/2784) - staking precompiled contract
* [2795](https://github.com/zeta-chain/node/pull/2795) - support restricted address in Solana
* [2861](https://github.com/zeta-chain/node/pull/2861) - emit events from staking precompile
* [2860](https://github.com/zeta-chain/node/pull/2860) - bank precompiled contract

### Refactor

Expand Down
4 changes: 4 additions & 0 deletions cmd/zetae2e/config/localnet.yml
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,10 @@ additional_accounts:
bech32_address: "zeta1nry9yeg6njhjrp2ctppa8558vqxal9fxk69zxg"
evm_address: "0x98c852651A9CAF2185585843d3D287600Ddf9526"
private_key: "bf9456c679bb5a952a9a137fcfc920e0413efdb97c36de1e57455763084230cb"
user_bank_precompile:
bech32_address: "zeta1qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqr84sgapz"
evm_address: "0x0000000000000000000000000000000000000067"
fbac marked this conversation as resolved.
Show resolved Hide resolved
private_key: ""
policy_accounts:
emergency_policy_account:
bech32_address: "zeta16m2cnrdwtgweq4njc6t470vl325gw4kp6s7tap"
Expand Down
1 change: 1 addition & 0 deletions cmd/zetae2e/local/local.go
Original file line number Diff line number Diff line change
Expand Up @@ -321,6 +321,7 @@ func localE2ETest(cmd *cobra.Command, _ []string) {
e2etests.TestPrecompilesPrototypeThroughContractName,
e2etests.TestPrecompilesStakingName,
e2etests.TestPrecompilesStakingThroughContractName,
e2etests.TestPrecompilesBankName,
}
}

Expand Down
1 change: 1 addition & 0 deletions codecov.yml
Original file line number Diff line number Diff line change
Expand Up @@ -82,3 +82,4 @@ ignore:
- "precompiles/**/*.sol"
- "precompiles/prototype/IPrototype.go"
- "precompiles/staking/IStaking.go"
- "precompiles/bank/IBank.go"
fbac marked this conversation as resolved.
Show resolved Hide resolved
12 changes: 1 addition & 11 deletions contrib/localnet/orchestrator/start-zetae2e.sh
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,7 @@ fund_eth_from_config '.additional_accounts.user_admin.evm_address' 10000 "admin
fund_eth_from_config '.additional_accounts.user_migration.evm_address' 10000 "migration tester"

# unlock precompile tests accounts
fund_eth_from_config '.additional_accounts.user_precompile.evm_address' 10000 "precompile tester"
fund_eth_from_config '.additional_accounts.user_precompile.evm_address' 10000 "precompiles tester"
fbac marked this conversation as resolved.
Show resolved Hide resolved

# unlock v2 ethers tests accounts
fund_eth_from_config '.additional_accounts.user_v2_ether.evm_address' 10000 "V2 ethers tester"
Expand All @@ -131,16 +131,6 @@ fund_eth_from_config '.additional_accounts.user_v2_ether_revert.evm_address' 100
# unlock v2 erc20 revert tests accounts
fund_eth_from_config '.additional_accounts.user_v2_erc20_revert.evm_address' 10000 "V2 ERC20 revert tester"

# unlock precompile tests accounts
address=$(yq -r '.additional_accounts.user_precompile.evm_address' config.yml)
echo "funding precompile tester address ${address} with 10000 Ether"
geth --exec "eth.sendTransaction({from: eth.coinbase, to: '${address}', value: web3.toWei(10000,'ether')})" attach http://eth:8545 > /dev/null

# unlock precompile tests accounts
address=$(yq -r '.additional_accounts.user_precompile.evm_address' config.yml)
echo "funding precompile tester address ${address} with 10000 Ether"
geth --exec "eth.sendTransaction({from: eth.coinbase, to: '${address}', value: web3.toWei(10000,'ether')})" attach http://eth:8545 > /dev/null

# unlock local solana relayer accounts
if host solana > /dev/null; then
solana_url=$(config_str '.rpcs.solana')
Expand Down
3 changes: 3 additions & 0 deletions contrib/localnet/scripts/start-zetacored.sh
Original file line number Diff line number Diff line change
Expand Up @@ -269,6 +269,9 @@ then
# v2 erc20 revert tester
address=$(yq -r '.additional_accounts.user_v2_erc20_revert.bech32_address' /root/config.yml)
zetacored add-genesis-account "$address" 100000000000000000000000000azeta
# bank precompile user
address=$(yq -r '.additional_accounts.user_bank_precompile.bech32_address' /root/config.yml)
zetacored add-genesis-account "$address" 100000000000000000000000000azeta
fbac marked this conversation as resolved.
Show resolved Hide resolved

# 3. Copy the genesis.json to all the nodes .And use it to create a gentx for every node
zetacored gentx operator 1000000000000000000000azeta --chain-id=$CHAINID --keyring-backend=$KEYRING --gas-prices 20000000000azeta
Expand Down
8 changes: 8 additions & 0 deletions e2e/e2etests/e2etests.go
Original file line number Diff line number Diff line change
Expand Up @@ -159,6 +159,8 @@ const (
TestPrecompilesPrototypeThroughContractName = "precompile_contracts_prototype_through_contract"
TestPrecompilesStakingName = "precompile_contracts_staking"
TestPrecompilesStakingThroughContractName = "precompile_contracts_staking_through_contract"
TestPrecompilesBankName = "precompile_contracts_bank"
TestPrecompilesBankThroughContractName = "precompile_contracts_bank_through_contract"
)

// AllE2ETests is an ordered list of all e2e tests
Expand Down Expand Up @@ -877,4 +879,10 @@ var AllE2ETests = []runner.E2ETest{
[]runner.ArgDefinition{},
TestPrecompilesStakingThroughContract,
),
runner.NewE2ETest(
TestPrecompilesBankName,
"test stateful precompiled contracts bank",
[]runner.ArgDefinition{},
TestPrecompilesBank,
),
}
119 changes: 119 additions & 0 deletions e2e/e2etests/test_precompiles_bank.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,119 @@
package e2etests

import (
"math/big"

"github.com/ethereum/go-ethereum/accounts/abi/bind"
"github.com/ethereum/go-ethereum/common"
"github.com/stretchr/testify/require"

"github.com/zeta-chain/node/e2e/runner"
"github.com/zeta-chain/node/e2e/utils"
"github.com/zeta-chain/node/precompiles/bank"
)

func TestPrecompilesBank(r *runner.E2ERunner, args []string) {
fbac marked this conversation as resolved.
Show resolved Hide resolved
require.Len(r, args, 0, "No arguments expected")

// Increase the gasLimit. It's required because of the gas consumed by precompiled functions.
previousGasLimit := r.ZEVMAuth.GasLimit
r.ZEVMAuth.GasLimit = 10_000_000
defer func() {
r.ZEVMAuth.GasLimit = previousGasLimit
}()

spender, bankAddr := r.EVMAddress(), bank.ContractAddress

// Create a bank contract caller.
bankContract, err := bank.NewIBank(bank.ContractAddress, r.ZEVMClient)
require.NoError(r, err, "Failed to create bank contract caller")

// Deposit and approve 50 WZETA for the test.
fbac marked this conversation as resolved.
Show resolved Hide resolved
fbac marked this conversation as resolved.
Show resolved Hide resolved
approveAmount := big.NewInt(0).Mul(big.NewInt(1e18), big.NewInt(50))
r.DepositAndApproveWZeta(approveAmount)

// Initial WZETA spender balance should be 50.
initialBalance, err := r.WZeta.BalanceOf(&bind.CallOpts{Context: r.Ctx}, spender)
require.NoError(r, err, "Error approving allowance for bank contract")
fbac marked this conversation as resolved.
Show resolved Hide resolved
require.EqualValues(r, approveAmount, initialBalance, "spender balance should be 50")

// Initial cosmos coin spender balance should be 0.
retBalanceOf, err := bankContract.BalanceOf(&bind.CallOpts{Context: r.Ctx}, r.WZetaAddr, spender)
require.NoError(r, err, "Error calling bank.balanceOf()")
require.EqualValues(r, uint64(0), retBalanceOf.Uint64(), "Initial cosmos coins balance has to be 0")

// Allow the bank contract to spend 25 WZeta tokens.
tx, err := r.WZeta.Approve(r.ZEVMAuth, bankAddr, big.NewInt(25))
require.NoError(r, err, "Error approving allowance for bank contract")
receipt := utils.MustWaitForTxReceipt(r.Ctx, r.ZEVMClient, tx, r.Logger, r.ReceiptTimeout)
require.EqualValues(r, uint64(1), receipt.Status, "approve allowance tx failed")
fbac marked this conversation as resolved.
Show resolved Hide resolved

// Check the allowance of the bank in WZeta tokens. Should be 25.
balance, err := r.WZeta.Allowance(&bind.CallOpts{Context: r.Ctx}, spender, bankAddr)
require.NoError(r, err, "Error retrieving bank allowance")
require.EqualValues(r, uint64(25), balance.Uint64(), "Error allowance for bank contract")

// Call Deposit with 25 coins.
tx, err = bankContract.Deposit(r.ZEVMAuth, r.WZetaAddr, big.NewInt(25))
require.NoError(r, err, "Error calling bank.deposit()")
receipt = utils.MustWaitForTxReceipt(r.Ctx, r.ZEVMClient, tx, r.Logger, r.ReceiptTimeout)

// Deposit event should be emitted.
depositEvent, err := bankContract.ParseDeposit(*receipt.Logs[0])
require.NoError(r, err)
require.Equal(r, big.NewInt(25).Uint64(), depositEvent.Amount.Uint64())
require.Equal(r, common.BytesToAddress(spender.Bytes()), depositEvent.Zrc20Depositor)
require.Equal(r, r.WZetaAddr, depositEvent.Zrc20Token)

// After deposit, cosmos coin spender balance should be 25.
retBalanceOf, err = bankContract.BalanceOf(&bind.CallOpts{Context: r.Ctx}, r.WZetaAddr, spender)
require.NoError(r, err, "Error calling bank.balanceOf()")
require.EqualValues(r, uint64(25), retBalanceOf.Uint64(), "balanceOf result has to be 25")

// After deposit, WZeta spender balance should be 25 less than initial.
finalBalance, err := r.WZeta.BalanceOf(&bind.CallOpts{Context: r.Ctx}, spender)
require.NoError(r, err, "Error retrieving final owner balance")
require.EqualValues(
r,
initialBalance.Uint64()-25, // expected
finalBalance.Uint64(), // actual
"Final balance should be initial - 25",
)

// After deposit, WZeta bank balance should be 25.
balance, err = r.WZeta.BalanceOf(&bind.CallOpts{Context: r.Ctx}, bankAddr)
require.NoError(r, err, "Error retrieving bank's balance")
require.EqualValues(r, uint64(25), balance.Uint64(), "Wrong locked WZeta amount in bank contract")

// Withdraw 15 coins to spender.
tx, err = bankContract.Withdraw(r.ZEVMAuth, r.WZetaAddr, big.NewInt(15))
require.NoError(r, err, "Error calling bank.withdraw()")
receipt = utils.MustWaitForTxReceipt(r.Ctx, r.ZEVMClient, tx, r.Logger, r.ReceiptTimeout)

// Withdraw event should be emitted.
withdrawEvent, err := bankContract.ParseWithdraw(*receipt.Logs[0])
require.NoError(r, err)
require.Equal(r, big.NewInt(15).Uint64(), withdrawEvent.Amount.Uint64())
require.Equal(r, common.BytesToAddress(spender.Bytes()), withdrawEvent.Zrc20Withdrawer)
require.Equal(r, r.WZetaAddr, withdrawEvent.Zrc20Token)

// After withdraw, WZeta spender balance should be only 10 less than initial. (25 - 15 = 10e2e/e2etests/test_precompiles_bank.go )
fbac marked this conversation as resolved.
Show resolved Hide resolved
afterWithdraw, err := r.WZeta.BalanceOf(&bind.CallOpts{Context: r.Ctx}, spender)
require.NoError(r, err, "Error retrieving final owner balance")
require.EqualValues(
r,
initialBalance.Uint64()-10, // expected
afterWithdraw.Uint64(), // actual
"Balance after withdraw should be initial - 10",
)

// After withdraw, cosmos coin spender balance should be 10.
retBalanceOf, err = bankContract.BalanceOf(&bind.CallOpts{Context: r.Ctx}, r.WZetaAddr, spender)
require.NoError(r, err, "Error calling bank.balanceOf()")
require.EqualValues(r, uint64(10), retBalanceOf.Uint64(), "balanceOf result has to be 10")

// Final WZETA bank balance should be 10.
balance, err = r.WZeta.BalanceOf(&bind.CallOpts{Context: r.Ctx}, bankAddr)
require.NoError(r, err, "Error retrieving bank's allowance")
require.EqualValues(r, uint64(10), balance.Uint64(), "Wrong locked WZeta amount in bank contract")
}
4 changes: 2 additions & 2 deletions e2e/e2etests/test_rate_limiter.go
Original file line number Diff line number Diff line change
Expand Up @@ -122,7 +122,7 @@ func createAndWaitWithdraws(r *runner.E2ERunner, withdrawType withdrawType, with
return err
}

duration := time.Now().Sub(startTime).Seconds()
duration := time.Since(startTime).Seconds()
block, err := r.ZEVMClient.BlockNumber(r.Ctx)
if err != nil {
return fmt.Errorf("error getting block number: %w", err)
Expand Down Expand Up @@ -155,7 +155,7 @@ func waitForWithdrawMined(
}

// record the time for completion
duration := time.Now().Sub(startTime).Seconds()
duration := time.Since(startTime).Seconds()
block, err := r.ZEVMClient.BlockNumber(ctx)
if err != nil {
return err
Expand Down
2 changes: 1 addition & 1 deletion e2e/e2etests/test_stress_btc_deposit.go
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ func monitorBTCDeposit(r *runner.E2ERunner, hash *chainhash.Hash, index int, sta
cctx.Index,
)
}
timeToComplete := time.Now().Sub(startTime)
timeToComplete := time.Since(startTime)
r.Logger.Print("index %d: deposit cctx success in %s", index, timeToComplete.String())

return nil
Expand Down
2 changes: 1 addition & 1 deletion e2e/e2etests/test_stress_btc_withdraw.go
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ func monitorBTCWithdraw(r *runner.E2ERunner, tx *ethtypes.Transaction, index int
cctx.Index,
)
}
timeToComplete := time.Now().Sub(startTime)
timeToComplete := time.Since(startTime)
r.Logger.Print("index %d: withdraw cctx success in %s", index, timeToComplete.String())

return nil
Expand Down
2 changes: 1 addition & 1 deletion e2e/e2etests/test_stress_eth_deposit.go
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ func monitorEtherDeposit(r *runner.E2ERunner, hash ethcommon.Hash, index int, st
cctx.Index,
)
}
timeToComplete := time.Now().Sub(startTime)
timeToComplete := time.Since(startTime)
r.Logger.Print("index %d: deposit cctx success in %s", index, timeToComplete.String())

return nil
Expand Down
2 changes: 1 addition & 1 deletion e2e/e2etests/test_stress_eth_withdraw.go
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ func monitorEtherWithdraw(r *runner.E2ERunner, tx *ethtypes.Transaction, index i
cctx.Index,
)
}
timeToComplete := time.Now().Sub(startTime)
timeToComplete := time.Since(startTime)
r.Logger.Print("index %d: withdraw cctx success in %s", index, timeToComplete.String())

return nil
Expand Down
Loading
Loading