owned this note
owned this note
Published
Linked with GitHub
# Sending native assets from L1 to L2 EVM addresses
Currently this is only possible by using the wasp-cli, which contains an internal wallet. The CLI uses the exposed API from Wasp to control the node.
It is responsible for administrative tasks such as deploying new chains and contracts, peering and metrics. Furthermore, it can request funds from a faucet and do minimal wallet specific operations like sending funds/assets, showing balance, generating new seeds.
For Firefly we need to recreate the L1 transaction with the correct metadata which is described in this document.
Furthermore, this document contains an example of querying L2 balances.
# Quick Overview
Wasp accesses the Tangle through Hornet.
Each Wasp node can host multiple smart contract chains.
One deployed chain contains one EVM chain.
Multiple Wasp nodes can form a committee which secures a specific chain.
A chain can also run by one single Wasp node, usually for testing.
These chains can be deployed and configured with the `wasp-cli`.
Interaction with smart contracts can be achieved with L1 and L2 (Off-Ledger) requests.
Transfering assets to EVM chains will happen through L1.
# Testing environment
To test the additions in Firefly and wallet.rs, a testing environment might become handy.
This is a quick setup guide for Hornet and Wasp.
At the time of writing the following node versions are used:
| Node | Branch | Commit |
| -------- | -------- | -------- |
| Hornet | develop | f93b189bf45649b506075f4d4b95555b738be813 |
| Wasp | develop | 3fd8d70ba0a60dead5ca1a026ac94cfdb5586c30 |
## Setup Hornet
Open a new shell for the Hornet node.
```bash
git clone git@github.com:iotaledger/hornet.git -b develop
cd hornet
git checkout f93b189bf45649b506075f4d4b95555b738be813
cd private_tangle
```
Read the `README.md` first, as you are required to gracefully shut down the first bootstrap process after a while.
Only exit the bootstrap process once you see a `coordinator.state` file inside `./hornet/private_tangle/privatedb/state`.
```bash
sudo ./bootstrap.sh build
<Ctrl-C>
sudo ./run.sh
```
Once the network is up and running, Wasp can be configured.
The shell will be blocked until the node is shut down. `<Ctrl-C>`
## Setup Wasp
Open a new shell for the Wasp node.
Building requires a newer installed Go version.
The version at the time of writing is: **go1.18.3**
```bash
git clone git@github.com:iotaledger/wasp.git -b develop
cd wasp
git checkout 3fd8d70ba0a60dead5ca1a026ac94cfdb5586c30
make build
./wasp
```
The shell will be blocked until the node is shut down. `<Ctrl-C>`
### Setup wasp-cli
The wasp-cli can be configured by using `wasp-cli set x y`, but to make it a quick setup, create a new empty `wasp-cli.json` inside the root folder (next to the wasp and wasp-cli binaries) and paste this configuration:
```json
{
"l1": {
"apiaddress": "http://localhost:14265",
"faucetaddress": "http://localhost:8091"
},
"wasp": {
"0": {
"api": "127.0.0.1:9090",
"nanomsg": "127.0.0.1:5550",
"peering": "127.0.0.1:4000"
}
}
}
```
Then initialize the wallet, request funds and deploy a chain.
```bash
# Generate a new seed
./wasp-cli init
# Request funds from the faucet
./wasp-cli request-funds
# Deploy a new chain with one single Wasp node (No actual committee)
./wasp-cli chain deploy --chain=evmchain --committee=0 --quorum=1
```
The deployment of the chain might take a while, the narrowed down output looks like this:
> creating new chain. Owner address:
> creating chain origin and init transaction
> sending committee record to nodes.. OK
> activating chain
You are now able to deposit assets to the EVM chain. To find an address to deposit to, the easiest way would be MetaMask. The configuration is to be found below.
Once Metamask is configured you can copy your address at this point:
![](https://i.imgur.com/fzPUQUK.png)
Then run
```
./wasp-cli chain deposit 0x7CceAeFD7ee8D4332b55f8DD6bf4eaa58B774a68 iota:1000000000
```
to deposit funds to the EVM address.
## Configuring MetaMask
It should now be possible to use Metamask to connect to the deployed chain, simply by using a preexisting or a new wallet.
Visit http://localhost:7000/chains (wasp:wasp) and click on the deployed chain id. Scroll down to the bottom and find the evm rpc url and the evm chain id.
Open up Metamask and configure it like so:
[Settings -> Networks -> Add Network]
![](https://i.imgur.com/WLAXeNZ.png)
You can check the actual balance of each address on the chain overview page, where the addresses are listed on the top.
# The deposit L1 request
A wallet can transfer native assets to L2 evm addresses by calling the core contract `account`. The core contract is responsible for managing L2 funds. In this use case, the function `transferAllowanceTo` is required.
## Structure
### Transaction
Output: BasicOutput
* Amount: IOTAs to send
* NativeTokens: Tokens to send
* Conditions:
* UnlockCondition:
* Address: ChainID
* Features:
* SenderFeature
* Address: L1 SenderAddress
* MetadataFeature
* Bytes: **Documented below**
### Metadata
The smart contract invocation metadata consists out of three parts.
* Which smart contract to call
* With which parameters
* With which allowance (defines which funds are actually moved)
Construct the first part of the metadata like this:
| Description | Type | Value | Additionals
| -------- | -------- | -------- | -------- |
| SenderContract | HName (uint32) | 0 | |
| TargetContract | HName (uint32) | 0x3C4B5E02 | HName("accounts") |
| ContractFunc | HName (uint32) | 0x23F4E3A1 | HName("transferAllowanceTo") |
| GasBudget | uint64 | 500000000 | This can be dynamic, but keep it as is for now |
This data gets written into a byte array as is.
**Example**:
```
metadata
.WriteUint32(0) // SenderContract
.WriteUint32(0x3C4B5E02) // TargetContract
.WriteUint32(0x23F4E3A1) // ContractFunc
.WriteUint64(500000000) // GasBudget
```
### Encoding and appending parameters
Contracts can receive additional parameters (Think of a `main(args)` function.) which are just appended to the byte array.
In our use case, we need to append two parameters.
Parameters are just `key,value pairs` internally. To save space, we use single characters as keys.
*This is the place where we define the evm target address.*
| Description | Type | Key | Value |
| -------- | -------- | -------- | -------- |
| EVM Target Address | uint8[21] | a | encoded EVM Address |
The EVM Address consists out of 21 bytes, which is encoded the following:
| Description | Type | Value |
| -------- | -------- | -------- |
| Address Type ID | uint8 | 3 |
| Address | uint8[20] | (example) 0xdbbD95E0340ebFCd14BFb4248cFdC31Da5bb4De8 |
`evmAddress = join(byte(3), hexToBytes(targetAddress))`
Make sure that the map is constructed from the lowest key to the highest (a,c)
```json
{
"a": targetAddress,
"c": 255,
}
```
**Encoding process**
* Write the length of the parameters `uint32(length(params))` (2)
* Iterate over the params
* Write the length of the key `uint16(length(key))` (1)
* Write the key `bytes(key)`
* Write the length of the value `uint32(length(value))`
* Write the value in bytes `bytes(value)`
**Example**
```go
params = {
"a": targetAddress,
"c": 255,
};
metadata.WriteUint32(uint32(len(params)))
for value, key := range params {
metadata.WriteUint16(uint16(len(key))).
WriteBytes([]byte(key)).
WriteUint32(uint32(len(value))).
WriteBytes(value)
}
```
### Encoding of the allowance
The allowance defines how much of the transferred assets actually land at the target address.
For example, it is possible to transfer 1000 IOTA, but the allowance only moves 500 IOTA.
In this case, 500 IOTA land at the target EVM address, the other 500 IOTA will land at the L2 account of the **sender** address.
For our use case, we most likely want to move all funds to the target address.
Therefore:
Allowance == Transferred Funds
It is encoded the following:
**Allowance**
| Description | Type | Value |
| -------- | -------- | -------- |
| IOTA Amount | uint64 | |
| Tokens | NativeToken[] | supplied token array |
**NativeToken**
| Description | Type |
| -------- | -------- |
| TokenID | uint8[38] |
| Amount | uint256 (big.Int) |
**NFT**
| Description | Type |
| -------- | -------- |
| TokenID | uint8[32] |
As with the params, the allowance just gets appended to the metadata the following way:
* Write `uint8(0)` if allowance is set, write `uint8(255)` if allowance is **not** set.
* If allowance is **not** set, return here
* Write `uint64(allowance.IOTA_Amount)`
* Write the amount of native tokens to a new Buffer (tokenBuffer)
* Iterate over the `Tokens` and write into the tokenBuffer:
* Write the tokenID `bytes(TokenID)`
* Write the amount `uint256(Amount)`
* Write length of token buffer `uint16(len(tokenBuffer))`
* Write token buffer `bytes(tokenBuffer)`
* Write `uint16(len(NftAmount))`
* Iterate over the `NFTs`:
* Write the NftID `bytes(NftId)`
**Example**
```json
allowance = {
IOTAs: 1000,
Tokens: [
{
TokenID: hexToBytes(0x08b2e20a58ee38d63c98aa705a740cc40e033885d353bf7982c8dca66d010f4e1f0100000000),
Amount: 1000
}
]
}
```
```go
tokenBuffer = NewBuffer();
metadata
.WriteUint8(0)
.WriteUint64(allowance.IOTAs)
tokenBuffer.writeUint16(len(allowance.Tokens))
for token, _ := range allowance.Tokens {
tokenBuffer
.WriteBytes(token.TokenID)
.WriteUint256(token.Amount)
}
metadata
.WriteUint16(len(tokenBuffer))
.WriteBytes(tokenBuffer)
```
In case NFTs are required, you can add the following data to the metadata.
***Note:** that you can only send 0 or 1 NFT*
```go
metadata.WriteUint16(uint16(len(allowance.NFTs)))
for _, id := range allowance.Tokens {
tokenBuffer
.WriteBytes(id)
}
```
The metadata is now complete and can be set to the Metadata feature.
# Querying L2 balances
Smart contracts can contain two different function types. One that allows read/write and one that only allows readings - which are called `views`.
Invoking functions with write permissions have a cost, views do not have any.
To query the balance of an L2 account, we can make use of the `balance` view function inside the `accounts (0x3c4b5e02)` core contract.
Wasp offers an API that clients can use to query any view function of any deployed contract.
This API is to be found on port `9090` by default. It also exposes a documentation on `http://localhost:9090/doc` if you want to test things or want to take a closer look.
## Request
The request to be used is:
**POST** `http://:9090/chain/<chainId>/contract/3c4b5e02/callview/balance`
Like with the `deposit` function above, views can also receive parameters.
These parameters are similarily encoded like in the example above, but are sent as an JSON object in the http request `body`. Furthermore, **all** keys and values need to be encoded as `base64`.
The one `Item` we need to add, is the encoded address we want to query the balance for.
It is encoded like in the example above:
`evmAddress = join(byte(3), hexToBytes(targetAddress))`
The JSON request object looks like this:
```json
{
"Items": [
{
"Key": base64.encode('a'),
"Value": base64.encode(evmAddress)
}
]
}
```
The API will respond with a similar JSON object containing the IOTA and assets balances:
```json
{
"Items": [
{
"Key":"",
"Value":"QYegjA=="
},
{
"Key":"CDc4W9l9Kul6KLsb5cGL6OhrQWyG9UtJGsVLtpb632EGAQAAAAA=",
"Value":"QYegjA=="
},
...
]
}
```
An empty Key in this response indicates the `IOTA balance`, as the tokenId is null.
All other assets will have a key with its encoded tokenId.
The IOTA Value will be encoded as a `Uint64BE`, native assets are encoded as `uint256 (big.Int)`
**Example**
A simple Go example can be found here: https://go.dev/play/p/vKPmiyB8yMj (click Run) a copy of the example can be found here: https://hackmd.io/pAsOzVQ5Tzal2CG8bBSV5A
It prints out a working Curl request that can be pasted into the terminal. It's just required to replace the `chain id` and the `target address`.
# Q & A
**1) What metadata is tied to a chain ID? What information can we get from the WASP node?**
*Currently not a lot of metadata is tied to a chain ID. Having information from the WASP node means that we need a connection with the WASP Node. This is not necessary (but could be a nice to have) for sending L1 -> L2. Having a connection is a good way to show whether a chain is active or not.*
**2) What does the gas budget mean for the user. Will they have a fix transaction fee for sending L1 -> L2, since it invokes a smart contract tx.**
*Gas budget ( = gas limit in Ethereum world). It is the max amount of gas a user will spend in the transaction. The actual amount spent for a L1 -> L2 is not refined at the moment. We definitely want a way of showing this to the user, so it would be great if a basic transaction could have a fix cost. If this depends on the transaction itself, we'll need to simulate the transaction (requires node connection) and show the estimated gas fee.*
**3) Do we enforce EVM-Addresses? What about WASM-Addresses?**
*Both EVM-Addresses and WASM VM-Addresses are supported. WASM VM-Addresses look the same as L1 addresses. For transactions to yourself it might be possible to omit the recipient address, since the WASP Node could derive this from the output sent to it. The same is not possible for EVM Addresses.*
**4) How does WASP node handle errors. What if something fails on L2 side?**
The WASP nodes consumes the basic output in the state transitioning of the smart contract. Does this mean that the basic output from the user goes into a new transaction with the previous alias output to produce the state update? Additionally there is blocklog on the WASP node which show the consumed transaction. This could also be used to check for failed transaction.
**5) What are the failure states?**
**6) How can we ensure we send to a smart contract**