Skip to main content

Integrating Ether wallet functionality

This tutorial will build a basic Ether wallet inside a Cartesi backend application using TypeScript.

The goal is to have a backend application to track balances and receive, transfer, and withdraw Ether.

community tools

This tutorial is for educational purposes. For production dApps, we recommend using Deroll, a TypeScript package that simplifies app and wallet functionality across all token standards for Cartesi applications.

Setting up the project

First, create a new TypeScript project using the Cartesi CLI.

cartesi create ether-wallet-dapp --template typescript

Run the following to generate the types for your project:

yarn && yarn run codegen

Now, navigate to the project directory and install ethers, viem and @cartesi/rollups package:

yarn add ethers viem
yarn add -D @cartesi/rollups@1.4.3

Define the ABIs

Let's write a configuration to generate the ABIs of the Cartesi Rollups Contracts.

We will need the Solidity compiler and the contract code from the @cartesi/rollups package to generate the ABIs as constants.

  1. Install the Solidity compiler.

  2. Create a new file named generate_abis.sh in the root of your project and add the following code:

#!/bin/bash

set -e # Exit immediately if a command exits with a non-zero status.

# Output directory for TypeScript files
TS_DIR="src/wallet/abi"

# Temporary directory for compilation output
TEMP_DIR="temp_solc_output"

# Create output and temporary directories
mkdir -p "$TS_DIR"
mkdir -p "$TEMP_DIR"

# Function to generate ABI and export as a TypeScript variable
generate_abi() {
local sol_file="$1"
local contract_name="$2"
local output_file="$TS_DIR/${contract_name}Abi.ts"

echo "Compiling $sol_file..."

# Compile the contract in the temporary directory
npx solcjs --abi "$sol_file" --base-path . --include-path node_modules/ --output-dir "$TEMP_DIR"

# Find the generated ABI file
abi_file=$(find "$TEMP_DIR" -name "*_${contract_name}.abi")

if [ ! -f "$abi_file" ]; then
echo "Error: ABI file not found for $contract_name"
return 1
fi

# Read the ABI content
abi=$(cat "$abi_file")

echo "Extracted ABI for $contract_name"

# Create a TypeScript file with exported ABI
echo "export const ${contract_name}Abi = $abi as const;" > "$output_file"

echo "Generated ABI for $contract_name"
echo "----------------------"
}

# Generate ABIs
generate_abi "node_modules/@cartesi/rollups/contracts/dapp/CartesiDApp.sol" "CartesiDApp"
generate_abi "node_modules/@cartesi/rollups/contracts/portals/EtherPortal.sol" "EtherPortal"

# Clean up the temporary directory
rm -rf "$TEMP_DIR"

echo "ABI generation complete"

This script will look for all specified .sol files and create a TypeScript file with the ABIs in the src/wallet/abi directory.

Now, let's make the script executable:

 chmod +x generate_abis.sh

And run it:

 ./generate_abis.sh

Building the Ether wallet

Our wallet will have two main classes: Balance and Wallet. Let's implement each of these:

Create a file named balance.ts in the src/wallet directory and add the following code:

import { Address } from "viem";

export class Balance {
constructor(
private readonly address: Address,
private ether: bigint = 0n
) {}

getEther(): bigint {
return this.ether;
}

increaseEther(amount: bigint): void {
if (amount < 0n) {
throw new Error(`Invalid amount: ${amount}`);
}
this.ether += amount;
}

decreaseEther(amount: bigint): void {
if (amount < 0n || this.ether < amount) {
throw new Error(`Invalid amount: ${amount}`);
}
this.ether -= amount;
}
}

The Balance class represents an individual account's balance. It includes methods for getting, increasing, and decreasing the Ether balance.

Now, create a file named wallet.ts in the src/wallet directory and add the following code:

import {
Address,
getAddress,
hexToBytes,
stringToHex,
encodeFunctionData,
numberToHex,
parseEther
} from "viem";
import { ethers } from "ethers";
import { Balance } from "./balance";
import { CartesiDAppAbi } from "./abi/CartesiDAppAbi";
import { Voucher } from "..";

export class Wallet {
private accounts: Map<string, Balance> = new Map();

private getOrCreateBalance(address: Address): Balance {
const key = address.toLowerCase();
if (!this.accounts.has(key)) {
this.accounts.set(key, new Balance(address));
}
return this.accounts.get(key)!;
}

getBalance(address: Address): bigint {
return this.getOrCreateBalance(address).getEther();
}

depositEther(payload: string): string {
const [address, amount] = this.parseDepositPayload(payload);
const balance = this.getOrCreateBalance(address);
balance.increaseEther(amount);
console.log(
`After deposit, balance for ${address} is ${balance.getEther()}`
);
return JSON.stringify({
type: "etherDeposit",
address,
amount: amount.toString(),
});
}

withdrawEther(
application: Address,
address: Address,
amount: bigint
): Voucher {
const balance = this.getOrCreateBalance(address);

if (balance.getEther() >= amount) {
balance.decreaseEther(amount);
const voucher = this.encodeWithdrawCall(application, address, amount);

console.log("Voucher created successfully", voucher);

return voucher;
} else {
throw Error("Insufficient balance");
}
}

transferEther(from: Address, to: Address, amount: bigint): string {
const fromBalance = this.getOrCreateBalance(from);
const toBalance = this.getOrCreateBalance(to);

if (fromBalance.getEther() >= amount) {
fromBalance.decreaseEther(amount);
toBalance.increaseEther(amount);
console.log(
`After transfer, balance for ${from} is ${fromBalance.getEther()}`
);
console.log(
`After transfer, balance for ${to} is ${toBalance.getEther()}`
);
return JSON.stringify({
type: "etherTransfer",
from,
to,
amount: amount.toString(),
});
} else {
throw Error("Insufficient amount");
}
}

private parseDepositPayload(payload: string): [Address, bigint] {
const addressData = ethers.dataSlice(payload, 0, 20);
const amountData = ethers.dataSlice(payload, 20, 52);
if (!addressData) {
throw new Error("Invalid deposit payload");
}
return [getAddress(addressData), BigInt(amountData)];
}

private encodeWithdrawCall(
application: Address,
receiver: Address,
amount: bigint
): Voucher {
const call = "0x"

return {
destination: receiver,
payload: call,
value: `${amount.toString(16).padStart(64, '0')}` as `0x${string}`,
};
}
}

The Wallet class manages multiple accounts and provides methods for everyday wallet operations. Key features include storing balances, centralizing the logic for retrieving or creating a balance, and depositing, withdrawing, and transferring Ether.

parseDepositPayload and encodeWithdrawCall handle the low-level details of working with the base layer data.

Voucher creation

The encodeWithdrawCall method returns a voucher. Creating vouchers is a crucial concept in Cartesi rollups for executing withdrawal operations on the base layer chain.

The Ether’s withdrawal voucher contains an empty payload (0x), this is because the function _executeVoucher(bytes calldata arguments) of the CartesiDapp makes a safecall to the destination (receiver) address passing the ether value (amount) and an empty payload, this call triggers the destination address receive function which collects the specified amount of Eth.

It returns a Voucher object with two properties:

  • destination: The address to receive the withdrawn Ether.
  • payload: An empty function calldata
  • value: A bytes encoding of the amount of Ether to withdraw.

Using the Ether wallet

Now, let's create a simple application at the entry point, src/index.ts, to test the wallet functionality.

The EtherPortal contract allows anyone to perform transfers of Ether to a dApp. All deposits to a dApp are made via the EtherPortal contract.

note

Run cartesi address-book to get the addresses of the EtherPortal contract. Save these as constants in the index.ts file.

import createClient from "openapi-fetch";
import type { components, paths } from "./schema";
import { Wallet } from "./wallet/wallet";
import { stringToHex, getAddress, Address, hexToString } from "viem";

type AdvanceRequestData = components["schemas"]["Advance"];
type InspectRequestData = components["schemas"]["Inspect"];
type RequestHandlerResult = components["schemas"]["Finish"]["status"];
type RollupRequest = components["schemas"]["RollupRequest"];
type InspectRequestHandler = (data: InspectRequestData) => Promise<void>;
type AdvanceRequestHandler = (
data: AdvanceRequestData
) => Promise<RequestHandlerResult>;

export type Notice = components["schemas"]["Notice"];
export type Payload = components["schemas"]["Payload"];
export type Report = components["schemas"]["Report"];
export type Voucher = components["schemas"]["Voucher"];

const wallet = new Wallet();
const EtherPortal = `0xd31aD6613bDaA139E7D12B2428C0Dd00fdBF8aDa`;

const rollupServer = process.env.ROLLUP_HTTP_SERVER_URL;
console.log(`HTTP rollup_server url is ${rollupServer}`);

const handleAdvance: AdvanceRequestHandler = async (data) => {
console.log(`Received advance request data ${JSON.stringify(data)}`);

const dAppAddress = data["metadata"]["app_contract"];
const sender = data["metadata"]["msg_sender"];
const payload = data.payload;

if (sender.toLowerCase() === EtherPortal.toLowerCase()) {
// Handle deposit
const deposit = wallet.depositEther(payload);
await createNotice({ payload: stringToHex(deposit) });
} else {
// Handle transfer or withdrawal
try {
const { operation, from, to, amount } = JSON.parse(hexToString(payload));

if (operation === "transfer") {
const transfer = wallet.transferEther(
getAddress(from as Address),
getAddress(to as Address),
BigInt(amount)
);
await createNotice({ payload: stringToHex(transfer) });
} else if (operation === "withdraw") {
const voucher = wallet.withdrawEther(
getAddress(dAppAddress as Address),
getAddress(from as Address),
BigInt(amount)
);

await createVoucher(voucher);
} else {
console.log("Unknown operation");
}
} catch (error) {
console.error("Error processing payload:", error);
}
}

return "accept";
};

const handleInspect: InspectRequestHandler = async (data) => {
console.log(`Received inspect request data ${JSON.stringify(data)}`);

try {
const address = hexToString(data.payload);
console.log(address);
const balance = wallet.getBalance(address as Address);

const reportPayload = `Balance for ${address} is ${balance} wei}`;
await createReport({ payload: stringToHex(reportPayload) });
} catch (error) {
console.error("Error processing inspect payload:", error);
}
};

const createNotice = async (payload: Notice) => {
console.log("creating notice with payload", payload);

await fetch(`${rollupServer}/notice`, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(payload),
});
};

const createVoucher = async (payload: Voucher) => {
await fetch(`${rollupServer}/voucher`, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(payload),
});
};

const createReport = async (payload: Report) => {
await fetch(`${rollupServer}/report`, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(payload),
});
};

const main = async () => {
const { POST } = createClient<paths>({ baseUrl: rollupServer });
let status: RequestHandlerResult = "accept";
while (true) {
const { data, response } = await POST("/finish", {
body: { status },
parseAs: "text",
});

if (response.status === 200 && data) {
const request = JSON.parse(data) as RollupRequest;
switch (request.request_type) {
case "advance_state":
status = await handleAdvance(request.data as AdvanceRequestData);
break;
case "inspect_state":
await handleInspect(request.data as InspectRequestData);
break;
}
} else if (response.status === 202) {
// no rollup request available
console.log(await response.text());
}
}
};

main().catch((e) => {
console.log(e);
process.exit(1);
});

This code sets up a simple application that listens for requests from the Cartesi rollup server. It processes the requests and sends responses back to the server.

Here is a breakdown of the wallet functionality:

  • The handle_advance handles three main scenarios: dApp address relay, Ether deposits, and user operations (transfers/withdrawals).

  • We handle deposits and create a notice when the sender is the EtherPortal.

  • We parse the payload for other senders to determine the operation (transfer or withdraw).

  • For transfers, we call wallet.transferEther and create a notice with the parsed parameters.

For withdrawals, we call wallet.withdrawEther and create a voucher using the dApp dress and the parsed parameters.

  • We created helper functions to createNotice for deposits and transfers, createReport for balance checks and createVoucher for withdrawals.
important

The dApp address needs to be relayed strictly before withdrawal requests.

To relay the dApp address, run: cartesi send dapp-address

Build and run the application

With Docker running, build your backend application by running:

cartesi build

To run your application, enter the command:

cartesi run

Deposits

To deposit ether, run the command below and follow the prompts:

cartesi deposit ether

Balance checks(used in Inspect requests)

To inspect balance, make an HTTP (post) call to:

curl -X POST http://127.0.0.1:6751/inspect/ether-wallet-dapp \
-H "Content-Type: application/json" \
-d '{0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266}'

Transfer and Withdrawals

Transfers and withdrawal requests will be sent as generic json strings that will be parsed and processed.

To process transfers and withdrawals, run the command below, select String encoding then follow the prompts:

cartesi send

Here are the sample payloads as one-liners, ready to be used in your code:

  1. For transfers:

    {"operation":"transfer","from":"0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266","to":"0x3f2bd12ea0b8604c2af5bf241f6a606e892a403a","amount":"1000000000000000000"}
  2. For withdrawals:

    {"operation":"withdraw","from":"0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266","amount":"1000000000000000000"}

Using the explorer

For end-to-end functionality, developers will likely build their custom user-facing web application.

CartesiScan is a web application that offers a comprehensive overview of your application. It provides expandable data regarding notices, vouchers, and reports.

When you run your application with cartesi run, there is a local instance of CartesiScan on http://localhost:8080/explorer.

You can execute your vouchers via the explorer, which completes the withdrawal process at the end of an epoch.

Repo Link

You can access the complete project implementation here!

We use cookies to ensure that we give you the best experience on our website. By using the website, you agree to the use of cookies.