Go API

WalletL2

Manages and interacts with accounts on L2

The WalletL2 class provides functionalities for managing and interacting with accounts on the Layer 2 (L2) network. It includes methods for creating wallets, querying balances, transferring tokens, and interacting with smart contracts on the ZKsync network.

Address

Returns the address of the associated account.

Address() common.Address

Example

fmt.Println("Address: ", wallet.Address())

AllBalances

Returns all balances for confirmed tokens given by an associated account.

Inputs

ParameterTypeDescription
ctxcontext.ContextContext.
AllBalances(ctx context.Context) (map[common.Address]*big.Int, error)

Example

balances, err := wallet.AllBalances(context.Background())
if err != nil {
            log.Panic(err)
}
fmt.Printf("Balances: %+v\n", balances)

Balance

Returns the balance of the specified token that can be either ETH or any ERC20 token. The block number can be nil, in which case the balance is taken from the latest known block.

Inputs

ParameterTypeDescription
ctxcontext.ContextContext.
tokencommon.AddressL2 token address.
at*big.IntBlock number.
Balance(ctx context.Context, token common.Address, at *big.Int) (*big.Int, error)

Example

balance, err := wallet.Balance(context.Background(), utils.EthAddress, nil)
if err != nil {
            log.Panic(err)
}
fmt.Println("Balance: ", balance)

CallContract

Executes a message call for EIP-712 transaction, which is directly executed in the VM of the node, but never mined into the blockchain.

Inputs

ParameterTypeDescription
ctxcontext.ContextContext.
msgCallMsgContains parameters for contract call using EIP-712 transaction.
blockNumber*big.Int (optional)Selects the block height at which the call runs. It can be nil, in which case the code is taken from the latest known block. Note that state from very old blocks might not be available.
CallContract(ctx context.Context, msg CallMsg, blockNumber *big.Int) ([]byte, error)

Example

// The Crown token on testnet
TokenAddress := common.HexToAddress("0x927488F48ffbc32112F1fF721759649A89721F8F")

tokenAbi, err := erc20.IERC20MetaData.GetAbi()
if err != nil {
            log.Panic(err)
}
symbolCalldata, err := tokenAbi.Pack("symbol")
if err != nil {
            log.Panic(err)
}

result, err := wallet.CallContract(context.Background(), types.CallMsg{
            CallMsg: ethereum.CallMsg{
                        To:   &TokenAddress,
                        Data: symbolCalldata,
            },
}, nil)
if err != nil {
            log.Panic(err)
}
unpack, err := tokenAbi.Unpack("symbol", result)
if err != nil {
            log.Panic(err)
}
symbol := *abi.ConvertType(unpack[0], new(string)).(*string)
fmt.Println("Symbol: ", symbol)

DeploymentNonce

Returns the deployment nonce of the account.

Inputs

ParameterTypeDescription
optsCallOpts (optional)Call options.
func (a *WalletL2) DeploymentNonce(opts *CallOpts) (*big.Int, error)

Example

deploymentNonce, err := wallet.DeploymentNonce(nil)
if err != nil {
    log.Panic(err)
}

EstimateGasTransfer

Estimates the amount of gas required for a transfer transaction.

Inputs

ParameterTypeDescription
ctxcontext.ContextContext.
msgTransferCallMsgTransfer call parameters.
EstimateGasTransfer(ctx context.Context, msg TransferCallMsg) (uint64, error)

Example

gas, err := wallet.EstimateGasTransfer(context.Background(), accounts.TransferCallMsg{
            To:   common.HexToAddress("<Receipt address>"),
            Amount: big.NewInt(7_000_000_000),
            Token:  utils.EthAddress,
})
if err != nil {
            log.Panic(err)
}
fmt.Println("Gas: ", gas)

EstimateGasWithdraw

Estimates the amount of gas required for a withdrawal transaction.

Inputs

ParameterTypeDescription
ctxcontext.ContextContext.
msgWithdrawalCallMsgWithdrawal call parameters.
EstimateGasWithdraw(ctx context.Context, msg WithdrawalCallMsg) (uint64, error)

Example

gas, err := wallet.EstimateGasWithdraw(context.Background(), accounts.WithdrawalCallMsg{
            To:   wallet.Address(),
            Amount: big.NewInt(7_000_000),
            Token:  utils.EthAddress,
})
if err != nil {
            log.Panic(err)
}
fmt.Println("Gas: ", gas)

Init

Creates an instance of WalletL2 associated with the account provided by the raw private key.

func NewWalletL2(rawPrivateKey []byte, client *clients.Client) (*WalletL2, error)

Creates an instance of WalletL2. The client can be optional; if it is not provided, only SignTransaction, Address, Signer can be performed, as the rest of the functionalities require communication to the network.

func NewWalletL2FromSigner(signer *Signer, client *clients.Client) (*WalletL2, error)

Example

PrivateKey     := os.Getenv("PRIVATE_KEY")
ZkSyncEraProvider := "https://testnet.era.zksync.dev"

client, err := clients.Dial(ZkSyncEraProvider)
if err != nil {
            log.Panic(err)
}
defer client.Close()

wallet, err := accounts.NewWallet(common.Hex2Bytes(PrivateKey), &client)
if err != nil {
            log.Panic(err)
}

IsBaseToken

Returns whether the token is the base token.

Inputs

ParameterTypeDescription
ctxcontext.ContextContext.
tokencommon.AddressToken address.
IsBaseToken(ctx context.Context, token common.Address) (bool, error)

Example

isBaseToken, err := wallet.IsBaseToken(
  context.Background(),
  common.HexToAddress("0x5C221E77624690fff6dd741493D735a17716c26B")
)
if err != nil {
    log.Panic(err)
}
fmt.Println("Is base token: ", isBaseToken)

L2BridgeContracts

Returns L2 bridge contracts.

Inputs

ParameterTypeDescription
ctxcontext.ContextContext.
L2BridgeContracts(ctx context.Context) (*zkTypes.L2BridgeContracts, error)

Example

contracts, err := wallet.L2BridgeContracts(context.Background())
if err != nil {
            log.Panic(err)
}

SendTransaction

Injects a transaction into the pending pool for execution. Any unset transaction fields are prepared using the PopulateTransaction method.

Inputs

ParameterTypeDescription
ctxcontext.ContextContext.
txTransactionTransaction parameters.
SendTransaction(ctx context.Context, tx *Transaction) (common.Hash, error)

Example

// The Crown token on testnet
TokenAddress := common.HexToAddress("0x927488F48ffbc32112F1fF721759649A89721F8F")
// Paymaster for Crown token on testnet
PaymasterAddress := common.HexToAddress("0x13D0D8550769f59aa241a41897D4859c87f7Dd46")
ReceiptAddress := common.HexToAddress("0xa61464658AfeAf65CccaaFD3a512b69A83B77618")

abi, err := erc20.IERC20MetaData.GetAbi()
if err != nil {
            log.Panic(err)
}

// Encode transfer function from token contract
calldata, err := abi.Pack("transfer", ReceiptAddress, big.NewInt(7))
if err != nil {
            log.Panic(err)
}

// Create paymaster parameters with encoded paymaster input
paymasterParams, err := utils.GetPaymasterParams(
            PaymasterAddress,
            &zkTypes.ApprovalBasedPaymasterInput{
                        Token:            TokenAddress,
                        MinimalAllowance: big.NewInt(1),
                        InnerInput:       []byte{},
            })
if err != nil {
            log.Panic(err)
}

hash, err := wallet.SendTransaction(context.Background(), &accounts.Transaction{
            To:   &TokenAddress,
            Data: calldata,
            Meta: &types.Eip712Meta{
                        PaymasterParams: paymasterParams,
            },
})
if err != nil {
            log.Panic(err)
}

_, err = client.WaitMined(context.Background(), hash)
if err != nil {
            log.Panic(err)
}

fmt.Println("Tx: ", hash)

Signer

Returns the signer of the associated account.

Signer() Signer

Example

fmt.Printf("Signer %+v\n", wallet.Signer())

SignTransaction

Returns a signed transaction that is ready to be broadcast to the network. The input transaction must be a valid transaction with all fields having appropriate values. To obtain a valid transaction, you can use the PopulateTransaction method.

Inputs

ParameterTypeDescription
txzkTypes.Transaction712EIP-712 transaction parameters.
SignTransaction(tx *zkTypes.Transaction712) ([]byte, error)

Example

// The Crown token on testnet
TokenAddress := common.HexToAddress("0x927488F48ffbc32112F1fF721759649A89721F8F")
// Paymaster for Crown token on testnet
PaymasterAddress := common.HexToAddress("0x13D0D8550769f59aa241a41897D4859c87f7Dd46")
ReceiptAddress := common.HexToAddress("0xa61464658AfeAf65CccaaFD3a512b69A83B77618")

abi, err := erc20.IERC20MetaData.GetAbi()
if err != nil {
            log.Panic(err)
}

// Encode transfer function from token contract
calldata, err := abi.Pack("transfer", ReceiptAddress, big.NewInt(7))
if err != nil {
            log.Panic(err)
}

preparedTx, err := wallet.PopulateTransaction(context.Background(), &accounts.Transaction{
            To:   &TokenAddress,
            Data: calldata,
})

signedTx, err := wallet.SignTransaction(preparedTx)
if err != nil {
            log.Panic(err)
}
fmt.Printf("Signed tx: %+v\n", signedTx)

Transfer

Moves the ETH or any ERC20 token from the associated account to the target account.

Inputs

ParameterTypeDescription
auth*TransactOpts (optional)Transaction options.
txTransferTransactionTransfer transaction parameters.
Transfer(auth *TransactOpts, tx TransferTransaction) (*types.Transaction, error)

Example

tx, err := wallet.Transfer(nil, accounts.TransferTransaction{
            To:     common.HexToAddress("<Receipt address>"),
            Amount: big.NewInt(7_000_000_000),
            Token:  utils.EthAddress,
})
if err != nil {
            log.Panic(err)
}
fmt.Println("Transaction: ", tx.Hash())

Withdraw

Initiates the withdrawal process which withdraws ETH or any ERC20 token from the associated account on L2 network to the target account on L1 network.

Inputs

ParameterTypeDescription
auth*TransactOpts (optional)Transaction options.
txWithdrawalTransactionWithdrawal transaction parameters.
Withdraw(auth *TransactOpts, tx WithdrawalTransaction) (*types.Transaction, error)

Example

tx, err := wallet.Withdraw(nil, accounts.WithdrawalTransaction{
            To:     wallet.Address(),
            Amount: big.NewInt(1_000_000_000_000_000_000),
            Token:  utils.EthAddress,
})
if err != nil {
            panic(err)
}
fmt.Println("Withdraw transaction: ", tx.Hash())

PopulateTransaction

Designed for users who prefer a simplified approach by providing only the necessary data to create a valid EIP-712 transaction. The only required fields are Transaction.To and either Transaction.Data or Transaction.Value (or both, if the method is payable). Any other fields that are not set will be prepared by this method.

Inputs

ParameterTypeDescription
ctxcontext.ContextContext.
txTransactionTransaction parameters.
PopulateTransaction(ctx context.Context, tx Transaction) (*zkTypes.Transaction712, error)

Example

// The Crown token on testnet
TokenAddress := common.HexToAddress("0x927488F48ffbc32112F1fF721759649A89721F8F")
// Paymaster for Crown token on testnet
PaymasterAddress := common.HexToAddress("0x13D0D8550769f59aa241a41897D4859c87f7Dd46")
ReceiptAddress := common.HexToAddress("0xa61464658AfeAf65CccaaFD3a512b69A83B77618")

abi, err := erc20.IERC20MetaData.GetAbi()
if err != nil {
            log.Panic(err)
}

// Encode transfer function from token contract
calldata, err := abi.Pack("transfer", ReceiptAddress, big.NewInt(7))
if err != nil {
            log.Panic(err)
}

preparedTx, err := wallet.PopulateTransaction(context.Background(), &accounts.Transaction{
            To:   &TokenAddress,
            Data: calldata,
})
fmt.Printf("Prepared tx: %+v\n", preparedTx)

Made with ❤️ by the ZKsync Community