Skip to main content

Asset handling

Assets exist on the base layer, where they have actual meaning and value.

As with any execution layer solution, a Cartesi Application that wants to manipulate assets needs a secure way of "teleporting" the assets from the base layer to the execution layer and when necessary, back to the base layer.

Currently, Cartesi Rollups support the following types of assets:

img

Deposits

Portals enable the safe transfer of assets from the base layer to the execution layer. Users authorize portals to deduct assets from their accounts and initiate transfers to the Application contract.

When an asset is deposited, it is on the base layer but gains a representation in the execution layer. The corresponding Portal contract sends an input via the InputBox contract describing the type of asset, amount, and some data the depositor might want the application to read. The off-chain machine will then interpret and validate the input payload.

Deposit input payloads are always specified as packed ABI-encoded parameters, as detailed below.

img

ABI encoding for deposits

AssetPacked ABI-encoded payload fieldsStandard ABI-encoded payload fields
Ether
  • address sender,
  • uint256 value,
  • bytes execLayerData
none
ERC-20
  • address token,
  • address sender,
  • uint256 amount,
  • bytes execLayerData
none
ERC-721
  • address token,
  • address sender,
  • uint256 tokenId,
  • standard ABI-encoded fields...
  • bytes baseLayerData,
  • bytes execLayerData
ERC-1155 (single)
  • address token,
  • address sender,
  • uint256 tokenId,
  • uint256 value,
  • standard ABI-encoded fields...
  • bytes baseLayerData,
  • bytes execLayerData
ERC-1155 (batch)
  • address token,
  • address sender,
  • standard ABI-encoded fields...
  • uint256[] tokenIds,
  • uint256[] values,
  • bytes baseLayerData,
  • bytes execLayerData

Refer to the functions provided below to understand how to handle asset deposits. When called inside your application's advance handler, these helpers decode the payload for the deposited asset type.

For example, to decode an ERC-20 deposit payload, you can use the following code snippets:

function decodeErc20Deposit(payloadHex) {
if (typeof payloadHex !== "string") {
throw new TypeError("payload must be a hex string");
}

const payload = payloadHex.startsWith("0x") ? payloadHex.slice(2) : payloadHex;
const raw = Buffer.from(payload, "hex");

// token(20) + sender(20) + amount(32) = 72 bytes
if (raw.length < 72) {
throw new Error("invalid ERC-20 deposit payload");
}

const token = `0x${raw.subarray(0, 20).toString("hex")}`.toLowerCase().trim();
const sender = `0x${raw.subarray(20, 40).toString("hex")}`.toLowerCase().trim();
const amount = BigInt(`0x${raw.subarray(40, 72).toString("hex")}`);
const exec_layer_data = raw.subarray(72);

return {
token,
sender,
amount,
exec_layer_data,
};
}

For a full guide, see the Tutorials: ERC-20 Token Wallet and Utilizing test tokens in dev environment.

Withdrawing assets

Users can deposit assets to a Cartesi Application, but only the Application can initiate withdrawals. When a withdrawal request is made, it’s processed and interpreted off-chain by the Cartesi Machine running the application’s code. Subsequently, the Cartesi Machine creates a voucher containing the necessary instructions for withdrawal, which is executable when an epoch has settled.

Withdrawing Tokens

Vouchers are crucial in allowing applications in the execution layer to interact with contracts in the base layer through message calls. They are emitted by the off-chain machine and executed by any participant in the base layer. Each voucher includes a destination address and a payload, typically encoding a function call for Solidity contracts.

The application’s off-chain layer often requires knowledge of its address to facilitate on-chain interactions for withdrawals, for example: transferFrom(sender, recipient, amount). In this case, the sender is the application itself.

Next, the off-chain machine uses the address of the application on the base layer to generate a voucher for execution at the executeOutput() function of the Application contract. This address is known to the offchain machine because it is embedded in the metadata of every input sent to the application, though the developer will need to implement extra logic fetch this address from the metadata then properly store and retrieve it when needed in situations like generating the above Voucher.

Below are multi-language examples showing how to transfer tokens to whoever calls the application. In each case, the encoded call data contains the token contract function and arguments (for example, recipient and amount). The voucher then includes a destination (the ERC-20 token contract), a payload (the encoded call data), and a value set to zero to indicate no Ether is sent with this transfer request.

import { encodeFunctionData, erc20Abi, hexToString, zeroHash } from "viem";

const rollup_server = process.env.ROLLUP_HTTP_SERVER_URL;
console.log("HTTP rollup_server url is " + rollup_server);

async function handle_advance(data) {
console.log("Received advance request data " + JSON.stringify(data));

const sender = data["metadata"]["msg_sender"];
const payload = hexToString(data.payload);
const erc20Token = "0x784f0c076CC55EAD0a585a9A13e57c467c91Dc3a"; // Sample ERC20 token address

const call = encodeFunctionData({
abi: erc20Abi,
functionName: "transfer",
args: [sender, BigInt(10)],
});

const voucher = {
destination: erc20Token,
payload: call,
value: zeroHash,
};

await emitVoucher(voucher);
return "accept";
}

const emitVoucher = async (voucher) => {
try {
await fetch(rollup_server + "/voucher", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(voucher),
});
} catch (error) {
// Do something when there is an error.
}
};

For a full guide, see the Tutorial: ERC-20 Token Wallet.

Withdrawing Ether

To execute Ether withdrawal it is important to emit a voucher with the necessary details as regarding whom you intend to send the Ether to and also the amount to send, nevertheless since the Application contract Executes vouchers by making a safeCall to the destination, passing a value (Ether amount to send along with the call) and a payload (function signature to call), it's acceptable to leave the payload section empty if you do not intend to call any functions in the destination address while sending just the specified value of Ether to the destination address. If you intend to call a payable function and also send Ether along, you can add a function signature matching the payable function you intend to call to the payload field.

Below are multi-language examples for Ether withdrawal. Here, the voucher sends Ether directly to an address instead of calling a token contract function, so there is no encoded function call payload.

import { hexToString, numberToHex, parseEther, zeroHash } from "viem";

const rollup_server = process.env.ROLLUP_HTTP_SERVER_URL;
console.log("HTTP rollup_server url is " + rollup_server);

async function handle_advance(data) {
console.log("Received advance request data " + JSON.stringify(data));

const sender = data["metadata"]["msg_sender"];
const payload = hexToString(data.payload);

const voucher = {
destination: sender,
payload: zeroHash,
value: numberToHex(BigInt(parseEther("1"))).slice(2),
};

await emitVoucher(voucher);
return "accept";
}

const emitVoucher = async (voucher) => {
try {
await fetch(rollup_server + "/voucher", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(voucher),
});
} catch (error) {
// Do something when there is an error.
}
};

For a full guide, see the Tutorial: Ether Wallet.

epoch length

By default, Cartesi nodes close one epoch every 7200 blocks. You can manually set the epoch length to facilitate quicker asset-handling methods.

Here are the function signatures used by vouchers to withdraw the different types of assets:

AssetDestinationFunction signature
EtherdApp contractwithdrawEther(address,uint256) 📄
ERC-20Token contracttransfer(address,uint256) 📄
ERC-20Token contracttransferFrom(address,address,uint256) 📄
ERC-721Token contractsafeTransferFrom(address,address,uint256) 📄
ERC-721Token contractsafeTransferFrom(address,address,uint256,bytes) 📄
ERC-1155Token contractsafeTransferFrom(address,address,uint256,uint256,data) 📄
ERC-1155Token contractsafeBatchTransferFrom(address,address,uint256[],uint256[],data) 📄
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.