Step 2: Modify the Backend for ETH Deposits
In this step, we’ll modify the backend to include a function that generates a deposit principal from a canister ID. This is essential for converting SepoliaETH into ckSepoliaETH, as per the ckEth documentation.
Installing the b3_utils
Rust Crate
First, we need to install the b3_utils Rust crate. Open your Cargo.toml
file and add the following line under [dependencies]
:
b3_utils = "0.8.0"
or run this command:
cargo add b3_utils
Modifying the greet
Function
Replace the existing greet
function with the new deposit_principal
function:
use b3_utils::{vec_to_hex_string_with_0x, Subaccount};
use candid::Principal;
#[ic_cdk::query]
fn deposit_principal(principal: String) -> String {
let principal = Principal::from_text(principal).unwrap();
let subaccount = Subaccount::from_principal(principal);
let bytes32 = subaccount.to_bytes32().unwrap();
vec_to_hex_string_with_0x(bytes32)
}
Why This Change?
-
Function Annotation: We use
#[ic_cdk::query]
to indicate that this is a query method, meaning it’s read-only and doesn’t modify the state. -
Principal Conversion: We convert the passed string into a
Principal
object, which is essential for generating a subaccount. -
Subaccount Generation: We generate a
Subaccount
from thePrincipal
, which is a necessary step for depositing ETH. -
Bytes32 Conversion: We convert the subaccount into a bytes32 array, which is the required format for the smart contract on the Sepolia Ethereum testnet.
-
Hex String: Finally, we convert the bytes32 array into a hex string with a “0x” prefix, which can be used as an argument for the smart contract.
Deploy the Modified Backend Canister
After making the changes to the backend, open another terminal and deploy the canister to your local Internet Computer environment using the following command:
yarn deploy hello
Note: confirm the conset with yes
the change on the terminal.
This will deploy only the hello
canister, which now includes the deposit_principal
function.
Update the Frontend Code
Navigate to the frontend code where the useActorMethod
hook is used. This is typically found in a component file. Change the method from "greet"
to "deposit_principal"
:
const { call, data, error, loading } = useActorMethod("deposit_principal")
Testing the Changes
-
Pass the Canister ID: Update the frontend to include an input field where you can enter the canister ID.
-
Check the Output: The output should be a hexadecimal string that represents the deposit principal, which can be used for depositing ETH.