Function gcore::prog::create_program

source ·
pub fn create_program(
    code_id: CodeId,
    salt: &[u8],
    payload: &[u8],
    value: u128,
) -> Result<(MessageId, ActorId)>
Expand description

Create a new program and returns its address.

This function creates a program initialization message.

Parameters:

  • code_id is the code identifier of newly creating program that is represented as blake2b hash;
  • salt is the arbitrary data needed to generate an address for a new program (control of salt uniqueness is entirely on the program developer’s side);
  • payload that can be used in the init function of the newly deployed “child” program;
  • value sent with the init message.

§Examples

Basically we can use “automatic” salt generation (“nonce”):

use gcore::{prog, CodeId};

static mut NONCE: i32 = 0;

fn increase() {
    unsafe { NONCE += 1 };
}

fn get() -> i32 {
    unsafe { NONCE }
}

#[no_mangle]
extern "C" fn handle() {
    // We assume we already have a code identifier
    let submitted_code: CodeId =
        hex_literal::hex!("abf3746e72a6e8740bd9e12b879fbdd59e052cb390f116454e9116c22021ae4a")
            .into();
    let (message_id, new_program_id) =
        prog::create_program(submitted_code, &get().to_le_bytes(), b"", 0)
            .expect("Unable to create a program");
    increase();
}

Another case for salt is to receive it as input:

use gcore::{msg, prog};

#[no_mangle]
extern "C" fn handle() {
    // ...
    let mut salt = vec![0u8; msg::size()];
    msg::read(&mut salt).expect("Unable to read");
    let (message_id, new_program_id) = prog::create_program(submitted_code, &salt, b"", 0)
        .expect("Unable to create a program");
}

Moreover, messages can be sent to a new program:

use gcore::{msg, prog};

#[no_mangle]
extern "C" fn handle() {
    // ...
    let (_, new_program_id) = prog::create_program(submitted_code, &salt, b"", 0)
        .expect("Unable to create a program");
    msg::send(new_program_id, b"payload for a new program", 0)
        .expect("Unable to send");
}