Skip to content

How to setup cycle payed in agent-rs update call? #591

@readygo67

Description

@readygo67
use ic_cdk_macros::{init, post_upgrade, pre_upgrade, query, update};
use ic_cdk::api::call::{msg_cycles_accept, msg_cycles_available};
use sha2::{Digest, Sha256};

const SINGLE_SHA256_COST_CYCLES :u64 = 200_000_000; 
const CONCAT_STRING_COST_CYCLES :u64 = 0; 

#[query]
pub fn greet()->String{
    format!("Hello, World!")
}

#[update]
pub fn sha256(msg :String, n :u32) -> String {
    let available_cycles = msg_cycles_available();
    let needed_cycles:u64 = SINGLE_SHA256_COST_CYCLES*(n as u64);
    ic_cdk::println!("needed_cycles: {}", needed_cycles);
    if available_cycles < needed_cycles{
        ic_cdk::eprintln!("Not enough cycles provided for sha256 operation.");
        return String::from("Not enough cycles provided for sha256 operation.");
    }
    let _ = msg_cycles_accept(needed_cycles);
    let mut input = msg.clone().into_bytes();
    ic_cdk::println!("input: {}", msg);
    for _ in 0..n {
        let mut hasher = Sha256::new();
        hasher.update(input);
        input = hasher.finalize().to_vec();
    }
    ic_cdk::println!("result: {}", hex::encode(input.clone()));
    hex::encode(input)
}

#[query]
pub fn concat(s1:String, s2:String) -> String {
    format!("{} {}", s1, s2) 
}

#[update]
pub fn concat_update(s1:String, s2:String) -> String {
    let available_cycles = msg_cycles_available();
    let needed_cycles:u64 = CONCAT_STRING_COST_CYCLES;
    if available_cycles < needed_cycles{
        ic_cdk::eprintln!("Not enough cycles provided for concat operation.");
        return String::from("Not enough cycles provided for concat operation.");
    }
    let _ = msg_cycles_accept(needed_cycles);
    format!("{} {}", s1, s2) 
}

If I want to call the concat_update by agent-rs, how can I attached cycles for the call?
in another words, how to achieve the following function using agent-rs

dfx canister call bkyz2-fmaaa-aaaaa-qaaaq-cai  sha256 '("Hello, World!")' --with-cycles 200000000 --wallet bnz7o-iuaaa-aaaaa-qaaaa-cai

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions