Introduction

Hi, I'm cardene, a software engineer and technical writer focused on blockchain and AI.

I've also authored Japanese technical books on specification-driven development with LLMs and decentralized application (DApp) development.

I also build and publish a variety of tools, libraries, and open-source projects.

This article demonstrates how to deploy a contract account using a specific input value to derive its deployment salt.

The example uses zKatana, the testnet for Astar zkEVM, an Ethereum Layer 2 network.

Deploying an ordinary contract account is relatively straightforward, but deriving its address from a particular input requires some additional work. The walkthrough uses an implementation I developed.

The code and network configuration reflect the environment available in December 2023. The historical endpoints, SDK interfaces, and deployments may no longer be available or supported.

What is account abstraction?

An illustration of account abstraction

A simplified way to describe account abstraction is that it allows a contract account to initiate account-level operations that would otherwise require an externally owned account.

Under the conventional Ethereum account model discussed here, there are two main types of accounts.

Account types

  • Externally owned accounts (EOAs)
  • Contract accounts

The two types have the following characteristics.

Externally owned accounts (EOAs)

EOAs

  • Controlled by a private key.
  • Can originate protocol-level transactions.

Contract accounts

Contract accounts

  • Do not have an associated private key of their own.
  • Execute contract code.

A conventional contract account cannot independently originate a protocol-level transaction in the same way as an EOA. It executes code when invoked, and that code can initiate further contract calls.

Account abstraction aims to reduce the distinction between EOAs and contract accounts by enabling users to authorize and initiate operations through programmable accounts. Under ERC-4337, a bundler submits the outer Ethereum transaction on behalf of the users.

The following article provides more detail.

https://mirror.xyz/0xcE77b9fCd390847627c84359fC1Bc02fC78f0e58/-qoixMc413uT4FFM61uhXYUiL05Hw-wahq9hV_JtjJs

ERC-4337

An illustration of ERC-4337

Implementing native account abstraction directly in the Ethereum protocol would require substantial changes.

To avoid relying on immediate changes to the protocol, ERC-4337 was proposed as a way to implement account abstraction on Ethereum using existing protocol capabilities.

The following articles provide a more detailed explanation.

https://mirror.xyz/0xcE77b9fCd390847627c84359fC1Bc02fC78f0e58/-qoixMc413uT4FFM61uhXYUiL05Hw-wahq9hV_JtjJs

Deploying a contract account

An illustration of contract account deployment

With that background, we can deploy a contract account whose address is derived in part from a specific input value.

Implementation overview

When deploying a contract account with mechanisms such as ERC-4337, there are two broad approaches.

Ways to deploy a contract account

  • Implement all the necessary components yourself.
  • Use an existing service or SDK.

Building every component yourself requires considerable effort, so developers commonly use an existing service.

There is a limitation, however: a service may not support the chain on which you want to deploy a contract account.

A hosted service generally depends on its supported networks, and developers may not be able to add arbitrary chains themselves. Newly launched or less widely used chains are therefore less likely to be supported.

The chain used in this example is zKatana, the testnet for Astar zkEVM.

In December 2023, the mainnet had not yet launched, and I had not found a contract-account deployment service that supported the testnet.

Stake Technologies, which was leading the development of Astar zkEVM, arranged support quickly, making an implementation using Gelato possible.

For more on Gelato, see the following article.

Gelato provides several blockchain infrastructure capabilities. It can be integrated with Safe to deploy and operate contract accounts.

The following starter kit and library provided the functionality needed to deploy contract accounts on zKatana.

https://github.com/gelatodigital/astar-zkatana-starter-kit

https://www.npmjs.com/package/zkatana-gelato-protocol-kit

The architecture looks like this.

Integration between Safe, Gelato, and the zKatana library

Gelato integrates with Safe. The zKatana-specific library adapts the contract-account deployment functionality for that testnet. For simplicity, the diagram refers to it as zKatana-Gelato, rather than using its full package name.

With the services and libraries identified, we can move on to the implementation.

Implementing the contract account

If you only need to deploy a conventional contract account, follow the documentation at the following pinned repository revision.

https://github.com/gelatodigital/astar-zkatana-starter-kit/tree/a77cd2534273eb4f12f789de69dccda34e897104

Deploying a contract account using a specific value

The main objective of this article is to deploy a contract account with a deployment salt derived from a specific input.

Here is the implementation.

javascript
import { ethers } from 'ethers';
import {
  PRIVATE_KEY,
  PROVIDER_URL,
  CONTRACT_ADDRESS,
  GELATO_RELAY_API_KEY,
} from './config';
import {
  EthAdapter,
  MetaTransactionData,
  MetaTransactionOptions,
  OperationType,
  RelayTransaction,
} from '@safe-global/safe-core-sdk-types';
import crypto from 'crypto';
import Safe, {
  EthersAdapter,
  SafeAccountConfig,
  SafeFactory,
  getSafeContract,
} from 'zkatana-gelato-protocol-kit';
import { GelatoRelayPack } from 'zkatana-gelato-relay-kit';
import ContractInfo from './abi.json';

const encryptSha256 = (value: string) => {
  console.log(`value: ${value}`);
  const hash = crypto.createHash('sha256').update(value, 'utf8').digest('hex');
  const decimalHash = String(BigInt(`0x${hash}`));
  return decimalHash;
};

const common = async (salt: string) => {
  const RPC_URL = PROVIDER_URL;
  const provider = new ethers.providers.JsonRpcProvider(RPC_URL);
  console.log('Network: ', await provider.getNetwork());
  const signer = new ethers.Wallet(PRIVATE_KEY, provider);
  const ethAdapterOwner = new EthersAdapter({
    ethers,
    signerOrProvider: signer,
  }) as EthAdapter;
  const safeFactory = await SafeFactory.create({ ethAdapter: ethAdapterOwner });
  const safeAccountConfig: SafeAccountConfig = {
    owners: [await signer.getAddress()],
    threshold: 1,
  };

  const saltNonce = encryptSha256(salt);
  console.log(`saltNonce: ${saltNonce}`);
  return {
    safeFactory: safeFactory,
    safeAccountConfig: safeAccountConfig,
    saltNonce: saltNonce,
    ethAdapterOwner: ethAdapterOwner,
    signer: signer,
  };
};

const createSafeWallet = async (salt: string) => {
  const { safeFactory, safeAccountConfig, saltNonce } = await common(salt);

  const safeSdk = await safeFactory.deploySafe({
    safeAccountConfig,
    saltNonce,
  });

  const safeAddress = await safeSdk.getAddress();
  console.log(`safeAddress: ${safeAddress}`);

  return safeAddress;
};

The code is lengthy, so the following sections explain it piece by piece.

Imports

javascript
import { ethers } from 'ethers';
import {
  PRIVATE_KEY,
  PROVIDER_URL,
  CONTRACT_ADDRESS,
  GELATO_RELAY_API_KEY,
} from './config';
import {
  EthAdapter,
  MetaTransactionData,
  MetaTransactionOptions,
  OperationType,
  RelayTransaction,
} from '@safe-global/safe-core-sdk-types';
import crypto from 'crypto';
import Safe, {
  EthersAdapter,
  SafeAccountConfig,
  SafeFactory,
  getSafeContract,
} from 'zkatana-gelato-protocol-kit';
import { GelatoRelayPack } from 'zkatana-gelato-relay-kit';
import ContractInfo from './abi.json';

This section imports the required libraries and files.

The config.ts file is defined as follows.

javascript
import * as dotenv from 'dotenv';
dotenv.config();

export const PRIVATE_KEY = process.env.NEXT_PUBLIC_PRIVATE_KEY as `0x${string}`;
export const GELATO_RELAY_API_KEY = process.env.NEXT_PUBLIC_GELATO_RELAY_API_KEY;
export const PROVIDER_URL = 'https://rpc.zkatana.gelato.digital';
export const CONTRACT_ADDRESS = '...';

Configuration

  • PRIVATE_KEY
    • The wallet's private key, read from an environment variable.
  • GELATO_RELAY_API_KEY
    • The Gelato API key used when arranging sponsored transaction gas payments through Gelato.
    • The following dashboard was used to configure the service and issue API keys.
    • https://app.gelato.network/relay
  • PROVIDER_URL
  • CONTRACT_ADDRESS
    • The token contract address used in the token operation shown later.

The example preserves the historical configuration, including the environment variable names. Do not expose real private keys or relay API keys in client-side code. In frameworks such as Next.js, the NEXT_PUBLIC_ prefix can make environment variables available to browser code; production signing and confidential API keys must remain in a protected execution environment.

The Gelato dashboard used in the example is shown below.

Historical Gelato relay configuration dashboard

javascript
import ContractInfo from './abi.json';

This import loads the ABI of the token contract used in the later example.

Hashing the input

javascript
const encryptSha256 = (value: string) => {
  console.log(`value: ${value}`);
  const hash = crypto.createHash('sha256').update(value, 'utf8').digest('hex');
  const decimalHash = String(BigInt(`0x${hash}`));
  return decimalHash;
};

Rather than supplying the input directly as a deployment salt, the example hashes it and converts the SHA-256 digest into a decimal string. This produces a deterministic salt value suitable for the SDK.

Hashing a value does not make a low-entropy input confidential or turn the salt into an authentication secret. The example also logs the input, so sensitive values should not be passed to it as written.

Shared logic

javascript
const common = async (salt: string) => {
  const RPC_URL = PROVIDER_URL;
  const provider = new ethers.providers.JsonRpcProvider(RPC_URL);
  console.log('Network: ', await provider.getNetwork());
  const signer = new ethers.Wallet(PRIVATE_KEY, provider);
  const ethAdapterOwner = new EthersAdapter({
    ethers,
    signerOrProvider: signer,
  }) as EthAdapter;
  const safeFactory = await SafeFactory.create({ ethAdapter: ethAdapterOwner });
  const safeAccountConfig: SafeAccountConfig = {
    owners: [await signer.getAddress()],
    threshold: 1,
  };

  const saltNonce = encryptSha256(salt);
  console.log(`saltNonce: ${saltNonce}`);
  return {
    safeFactory: safeFactory,
    safeAccountConfig: safeAccountConfig,
    saltNonce: saltNonce,
    ethAdapterOwner: ethAdapterOwner,
    signer: signer,
  };
};

This function defines the common logic used when deploying the contract account, retrieving its address, or performing the token operation.

It initializes the provider, signer, adapter, and Safe factory, configures a single-owner Safe with a threshold of one, derives the salt nonce from the supplied value, and returns the required configuration and SDK objects.

Deploying the contract account

javascript
const createSafeWallet = async (salt: string) => {
  const { safeFactory, safeAccountConfig, saltNonce } = await common(salt);

  const safeSdk = await safeFactory.deploySafe({
    safeAccountConfig,
    saltNonce,
  });

  const safeAddress = await safeSdk.getAddress();
  console.log(`safeAddress: ${safeAddress}`);

  return safeAddress;
};

This is where the contract account is deployed, through the call to safeFactory.deploySafe.

Once deployment succeeds, the function returns the address of the Safe contract account.

The SDK makes this portion of the implementation fairly straightforward.

That completes the process of deploying a contract account using a specific value to derive its salt. The resulting address also depends on the deployment factory, account initialization data, and other relevant deployment parameters; the salt alone does not determine it.

Deploying an account is not enough for a DApp. We also need to use that account to execute contract calls, which the following section demonstrates.

Executing operations through the contract account

An illustration of contract execution through the deployed account

Now that the contract account has been deployed, we can execute a contract call through it.

The code builds on the implementation from the previous section.

Retrieving the contract account address

First, retrieve the address of the contract account. The code is as follows.

javascript
const getSafeWallet = async (salt: string) => {
  const { safeFactory, safeAccountConfig, saltNonce, ethAdapterOwner, signer } =
    await common(salt);

  const safeWalletAddress = await safeFactory.predictSafeAddress(
    safeAccountConfig,
    saltNonce
  );

  const safeSDK = await Safe.create({
    ethAdapter: ethAdapterOwner,
    safeAddress: safeWalletAddress,
  });

  console.log(`safeSDK address: ${await safeSDK.getAddress()}`);

  return { safeSDK, signer, ethAdapterOwner };
};

The common function obtains the shared configuration and SDK objects.

javascript
const safeWalletAddress = await safeFactory.predictSafeAddress(
    safeAccountConfig,
    saltNonce
);

The factory predicts the Safe address using the account configuration and salt nonce.

javascript
const safeSDK = await Safe.create({
    ethAdapter: ethAdapterOwner,
    safeAddress: safeWalletAddress,
});
console.log(`safeSDK address: ${await safeSDK.getAddress()}`);

The SDK then creates an instance associated with that predicted address.

Despite the name of Safe.create, this call does not deploy a new contract account. It initializes the SDK for the address of the previously deployed account. Address prediction itself does not establish that a contract has already been deployed at that address.

This completes the process of retrieving the contract account.

Performing the token operation

Finally, we can use the contract account to execute a token operation.

The following token contract is used in the example.

solidity
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;

import "@openzeppelin/contracts/token/ERC20/ERC20.sol";

contract Token is ERC20 {

    event TokenTransfer(address indexed from, address indexed to, uint256 amount, string longitude, string latitude, string message);

    constructor() ERC20("Token", "TK") {}

    function mint(address from, address to, uint256 amount, string calldata longitude, string calldata latitude, string calldata message) public {
        _mint(to, amount);

        emit TokenTransfer(from, to, amount, longitude, latitude, message);
    }

}

It is a simple contract whose minting function accepts several additional values.

The next code listing demonstrates how to call the token contract through the contract account.

javascript
export const sendToken = async (
    salt: string,
    to: string,
  message: string,
  longitude: string,
    latitude: string
) => {
  const { safeSDK, signer, ethAdapterOwner } = await getSafeWallet(salt);
  const tokenContract = new ethers.Contract(
    CONTRACT_ADDRESS,
    ContractInfo.abi,
    signer
  );
  console.log(`tokenContract: ${tokenContract}`);
  const aaWalletAddress: string = await safeSDK.getAddress();
  console.log(`aaWalletAddress: ${aaWalletAddress}`);

  const safeTransactionData: MetaTransactionData[] = [
    {
      to: CONTRACT_ADDRESS,
      data: tokenContract.interface.encodeFunctionData('mint', [
        aaWalletAddress,
        to,
        1,
        longitude,
        latitude,
        message,
      ]),
      value: '0',
      operation: OperationType.Call,
    },
  ];

  console.log(`safeTransactionData: ${JSON.stringify(safeTransactionData)}`);

  const relayKit = new GelatoRelayPack(GELATO_RELAY_API_KEY);

  const options: MetaTransactionOptions = {
    gasLimit: "8000000",
    isSponsored: true
  }

  const safeTransaction = await relayKit.createRelayedTransaction({
    safe: safeSDK,
    transactions: safeTransactionData,
    options,
  });

  const safeSingletonContract = await getSafeContract({
    ethAdapter: ethAdapterOwner,
    safeVersion: await safeSDK.getContractVersion(),
  });

  const signedSafeTransaction = await safeSDK.signTransaction(safeTransaction);

  console.log(
    `signedSafeTransaction: ${JSON.stringify(signedSafeTransaction)}`
  );

  const encodedTx = safeSingletonContract.encode("execTransaction", [
    signedSafeTransaction.data.to,
    signedSafeTransaction.data.value,
    signedSafeTransaction.data.data,
    signedSafeTransaction.data.operation,
    signedSafeTransaction.data.safeTxGas,
    signedSafeTransaction.data.baseGas,
    signedSafeTransaction.data.gasPrice,
    signedSafeTransaction.data.gasToken,
    signedSafeTransaction.data.refundReceiver,
    signedSafeTransaction.encodedSignatures(),
  ]);

  const relayTransaction: RelayTransaction = {
    target: aaWalletAddress,
    encodedTransaction: encodedTx,
    chainId: 1261120,
    options,
  };

  const response = await relayKit.relayTransaction(relayTransaction);

  console.log(
    `Relay Transaction Task ID: https://relay.gelato.digital/tasks/status/${response.taskId}`
  );

  console.log(`response: ${JSON.stringify(response)}`);
  return response.taskId
};

The following sections explain the main parts of this implementation.

javascript
const { safeSDK, signer, ethAdapterOwner } = await getSafeWallet(salt);
const tokenContract = new ethers.Contract(
    CONTRACT_ADDRESS,
    ContractInfo.abi,
    signer
);
console.log(`tokenContract: ${tokenContract}`);
const aaWalletAddress: string = await safeSDK.getAddress();
console.log(`aaWalletAddress: ${aaWalletAddress}`);

First, retrieve the contract account deployed earlier and initialize the token contract interface.

javascript
const safeTransactionData: MetaTransactionData[] = [
    {
      to: CONTRACT_ADDRESS,
      data: tokenContract.interface.encodeFunctionData('mint', [
        aaWalletAddress,
        to,
        1,
        longitude,
        latitude,
        message,
      ]),
      value: '0',
      operation: OperationType.Call,
    },
];

console.log(`safeTransactionData: ${JSON.stringify(safeTransactionData)}`);

const relayKit = new GelatoRelayPack(GELATO_RELAY_API_KEY);

const options: MetaTransactionOptions = {
    gasLimit: "8000000",
    isSponsored: true
}

const safeTransaction = await relayKit.createRelayedTransaction({
    safe: safeSDK,
    transactions: safeTransactionData,
    options,
});

This defines the information needed for the contract call, including the target contract and the encoded mint function call.

javascript
const safeSingletonContract = await getSafeContract({
    ethAdapter: ethAdapterOwner,
    safeVersion: await safeSDK.getContractVersion(),
});

const signedSafeTransaction = await safeSDK.signTransaction(safeTransaction);

console.log(
    `signedSafeTransaction: ${JSON.stringify(signedSafeTransaction)}`
);

const encodedTx = safeSingletonContract.encode("execTransaction", [
    signedSafeTransaction.data.to,
    signedSafeTransaction.data.value,
    signedSafeTransaction.data.data,
    signedSafeTransaction.data.operation,
    signedSafeTransaction.data.safeTxGas,
    signedSafeTransaction.data.baseGas,
    signedSafeTransaction.data.gasPrice,
    signedSafeTransaction.data.gasToken,
    signedSafeTransaction.data.refundReceiver,
    signedSafeTransaction.encodedSignatures(),
]);

const relayTransaction: RelayTransaction = {
    target: aaWalletAddress,
    encodedTransaction: encodedTx,
    chainId: 1261120,
    options,
};

This section prepares the information and signatures required to execute the call through the Safe contract account.

javascript
const response = await relayKit.relayTransaction(relayTransaction);

console.log(
    `Relay Transaction Task ID: https://relay.gelato.digital/tasks/status/${response.taskId}`
);

console.log(`response: ${JSON.stringify(response)}`);
return response.taskId

The transaction is submitted to the relay service. The response contains a task ID that can be used to construct a status URL.

At the time of the example, opening the following URL displayed the corresponding transaction details.

https://relay.gelato.digital/tasks/status/0x03...

This completes the contract execution example. A relay task ID indicates that a request has been submitted; verify the relay result and on-chain transaction receipt before treating the operation as successful.

Working through the example locally in a compatible environment is a useful way to understand the interaction between the SDKs and the contract account.

References

References for the Safe and Gelato integration

Because the implementation uses several services and SDKs, including Safe and Gelato, the following documentation provides useful reference material for investigating the original implementation.

https://github.com/gelatodigital/astar-zkatana-starter-kit/tree/a77cd2534273eb4f12f789de69dccda34e897104

Conclusion

Summary of the contract account deployment example

This article demonstrated how to deploy a contract account on zKatana using a specific value to derive the deployment salt.

The same general approach may be adapted to chains other than zKatana. Check that the target chain supports the required Safe factory and implementation contracts, SDK versions, and relay infrastructure before adapting the example.