Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Soroban: Support for Constructors #1675

Open
wants to merge 5 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 0 additions & 1 deletion integration/soroban/.gitignore
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
*.js
*.so
*.key
*.json
Expand Down
11 changes: 11 additions & 0 deletions integration/soroban/constructor_no_args.sol
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
contract noargsconstructor {
uint64 public count = 1;

constructor() {
count += 1;
}

function get() public view returns (uint64) {
return count;
}
}
41 changes: 41 additions & 0 deletions integration/soroban/noargsconstructor.spec.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import * as StellarSdk from '@stellar/stellar-sdk';
import { readFileSync } from 'fs';
import { expect } from 'chai';
import path from 'path';
import { fileURLToPath } from 'url';
import { call_contract_function } from './test_helpers.js';

const __filename = fileURLToPath(import.meta.url);
const dirname = path.dirname(__filename);

describe('CounterWithNoArgsConstructor', () => {
let keypair;
const server = new StellarSdk.SorobanRpc.Server(
"https://soroban-testnet.stellar.org:443",
);

let contractAddr;
let contract;
before(async () => {

console.log('Setting up counter with no-args constructor contract tests...');

// read secret from file
const secret = readFileSync('alice.txt', 'utf8').trim();
keypair = StellarSdk.Keypair.fromSecret(secret);

let contractIdFile = path.join(dirname, '.soroban', 'contract-ids', 'noargsconstructor.txt');
// read contract address from file
contractAddr = readFileSync(contractIdFile, 'utf8').trim().toString();

// load contract
contract = new StellarSdk.Contract(contractAddr);
});

it('make sure the constructor of the contract was called', async () => {
// get the count
let count = await call_contract_function("get", server, keypair, contract);
expect(count.toString()).eq("2");
});

});
1 change: 1 addition & 0 deletions integration/soroban/setup.js
Original file line number Diff line number Diff line change
Expand Up @@ -60,4 +60,5 @@ function add_testnet() {

add_testnet();
generate_alice();
// FIXME: This will need to be refactored to allow providing constructor arguments for a specific contract
deploy_all();
22 changes: 18 additions & 4 deletions src/emit/soroban/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ impl SorobanTarget {
);
binary.internalize(export_list.as_slice());

Self::emit_initializer(&mut binary, ns);
Self::emit_initializer(&mut binary, ns, contract.constructors(ns).first());

Self::emit_env_meta_entries(context, &mut binary, opt);

Expand Down Expand Up @@ -262,15 +262,17 @@ impl SorobanTarget {
);
}

fn emit_initializer(binary: &mut Binary, _ns: &ast::Namespace) {
fn emit_initializer(
binary: &mut Binary,
_ns: &ast::Namespace,
constructor_cfg_no: Option<&usize>,
) {
let mut cfg = ControlFlowGraph::new("__constructor".to_string(), ASTFunction::None);

cfg.public = true;
let void_param = ast::Parameter::new_default(ast::Type::Void);
cfg.returns = sync::Arc::new(vec![void_param]);

Self::emit_function_spec_entry(binary.context, &cfg, "__constructor".to_string(), binary);

let function_name = CString::new(STORAGE_INITIALIZER).unwrap();
let mut storage_initializers = binary
.functions
Expand All @@ -294,8 +296,20 @@ impl SorobanTarget {
.build_call(storage_initializer, &[], "storage_initializer")
.unwrap();

// call the user defined constructor (if any)
if let Some(cfg_no) = constructor_cfg_no {
let constructor = binary.functions[cfg_no];
let constructor_name = constructor.get_name().to_str().unwrap();
binary
.builder
.build_call(constructor, &[], constructor_name)
.unwrap();
}
Comment on lines +299 to +307
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We can set cfg.params to the parameters of the constructor FunctionValue's params. This will likely include a mapping that looks something like:

let mut params = vec![];
for param in constructor.get_params() {
	let param = match param.get_type() {
		BasicTypeEnum::IntType(int_type) => {
			let ty = match int_type.get_bit_width() {
				1 => ast::Type::Bool,
				32 => ast::Type::Uint(32),
				64 => ast::Type::Uint(64),
				_ => unreachable!(),
			};
			ast::Parameter::new_default(ty)
		}
		_ => unreachable!(),
	};
	params.push(param);
}
cfg.params = sync::Arc::new(params);

This won’t work because we still need to pass the arguments to build_call() (on line 296), which, of course, we don’t know.


// return zero
let zero_val = binary.context.i64_type().const_int(2, false);
binary.builder.build_return(Some(&zero_val)).unwrap();

Self::emit_function_spec_entry(binary.context, &cfg, "__constructor".to_string(), binary);
}
}
28 changes: 18 additions & 10 deletions tests/soroban.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,8 @@ pub struct SorobanEnv {
contracts: Vec<Address>,
}

pub fn build_solidity(src: &str) -> SorobanEnv {
/// Compile a Solidity contract and return the compiled WASM blob.
pub fn build_solidity(src: &str) -> Vec<u8> {
let tmp_file = OsStr::new("test.sol");
let mut cache = FileResolver::default();
cache.set_file_contents(tmp_file.to_str().unwrap(), src.to_string());
Expand All @@ -40,35 +41,42 @@ pub fn build_solidity(src: &str) -> SorobanEnv {
);
ns.print_diagnostics_in_plain(&cache, false);
assert!(!wasm.is_empty());
let wasm_blob = wasm[0].0.clone();
SorobanEnv::new_with_contract(wasm_blob)
wasm[0].0.clone()
}

impl SorobanEnv {
/// Create a new Soroban environment.
pub fn new() -> Self {
Self {
env: Env::default(),
contracts: Vec::new(),
}
}

pub fn new_with_contract(contract_wasm: Vec<u8>) -> Self {
/// Create a new Soroban environment with a contract.
pub fn new_with_contract(
contract_wasm: Vec<u8>,
constructor_args: soroban_sdk::Vec<Val>,
) -> Self {
let mut env = Self::new();
env.register_contract(contract_wasm);
env.register_contract(contract_wasm, constructor_args);
env
}

pub fn register_contract(&mut self, contract_wasm: Vec<u8>) -> Address {
// For now, we keep using `register_contract_wasm`. To use `register`, we have to figure
// out first what to pass for `constructor_args`
#[allow(deprecated)]
/// Register a contract given its WASM blob and constructor arguments.
pub fn register_contract(
&mut self,
contract_wasm: Vec<u8>,
constructor_args: soroban_sdk::Vec<Val>,
) -> Address {
let addr = self
.env
.register_contract_wasm(None, contract_wasm.as_slice());
.register(contract_wasm.as_slice(), constructor_args);
self.contracts.push(addr.clone());
addr
}

/// Invoke a contract and return the result.
pub fn invoke_contract(&self, addr: &Address, function_name: &str, args: Vec<Val>) -> Val {
let func = Symbol::new(&self.env, function_name);
let mut args_soroban = vec![&self.env];
Expand Down
94 changes: 94 additions & 0 deletions tests/soroban_testcases/constructor.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
// SPDX-License-Identifier: Apache-2.0

use crate::{build_solidity, SorobanEnv};
use soroban_sdk::testutils::Logs;
use soroban_sdk::{IntoVal, Val};

#[test]
fn test_constructor_increments_count() {
let wasm = build_solidity(
r#"contract counter {
uint64 public count = 1;

constructor() {
count += 1;
}

function get() public view returns (uint64) {
return count;
}
}"#,
);
let mut src = SorobanEnv::new();
// No constructor arguments
let constructor_args: soroban_sdk::Vec<Val> = soroban_sdk::Vec::new(&src.env);
let address = src.register_contract(wasm, constructor_args);

let res = src.invoke_contract(&address, "get", vec![]);
let expected: Val = 2_u64.into_val(&src.env);
assert!(
expected.shallow_eq(&res),
"expected: {:?}, got: {:?}",
expected,
res
);
}

#[test]
fn test_constructor_logs_message_on_call() {
let wasm = build_solidity(
r#"contract counter {
uint64 public count = 1;

constructor() {
print("Constructor called");
}

function get() public view returns (uint64) {
return count;
}
}"#,
);
let mut src = SorobanEnv::new();
// No constructor arguments
let constructor_args: soroban_sdk::Vec<Val> = soroban_sdk::Vec::new(&src.env);
let address = src.register_contract(wasm, constructor_args);

let _res = src.invoke_contract(&address, "get", vec![]);

let logs = src.env.logs().all();
assert!(logs[0].contains("Constructor called"));
}

// FIXME: Uncomment this test once the constructor arguments are supported
// #[test]
fn _test_constructor_set_count_value() {
let wasm = build_solidity(
r#"contract counter {
uint64 public count = 1;

constructor(uint64 initial_count) {
count = initial_count;
}

function get() public view returns (uint64) {
return count;
}
}"#,
);
let mut src = SorobanEnv::new();
let mut constructor_args: soroban_sdk::Vec<Val> = soroban_sdk::Vec::new(&src.env);
constructor_args.push_back(42_u64.into_val(&src.env));
let address = src.register_contract(wasm, constructor_args);

// Get the value of count and check it is 42
let res = src.invoke_contract(&address, "get", vec![]);
let expected: Val = 42_u64.into_val(&src.env);

assert!(
expected.shallow_eq(&res),
"expected: {:?}, got: {:?}",
expected,
res
);
}
31 changes: 18 additions & 13 deletions tests/soroban_testcases/math.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
// SPDX-License-Identifier: Apache-2.0

use crate::build_solidity;
use crate::{build_solidity, SorobanEnv};
use soroban_sdk::{IntoVal, Val};

#[test]
fn math() {
let runtime = build_solidity(
let wasm = build_solidity(
r#"contract math {
function max(uint64 a, uint64 b) public returns (uint64) {
if (a > b) {
Expand All @@ -16,20 +16,23 @@ fn math() {
}
}"#,
);
let mut env = SorobanEnv::new();
// No constructor arguments
let constructor_args: soroban_sdk::Vec<Val> = soroban_sdk::Vec::new(&env.env);
let address = env.register_contract(wasm, constructor_args);

let arg: Val = 5_u64.into_val(&runtime.env);
let arg2: Val = 4_u64.into_val(&runtime.env);
let arg: Val = 5_u64.into_val(&env.env);
let arg2: Val = 4_u64.into_val(&env.env);

let addr = runtime.contracts.last().unwrap();
let res = runtime.invoke_contract(addr, "max", vec![arg, arg2]);
let res = env.invoke_contract(&address, "max", vec![arg, arg2]);

let expected: Val = 5_u64.into_val(&runtime.env);
let expected: Val = 5_u64.into_val(&env.env);
assert!(expected.shallow_eq(&res));
}

#[test]
fn math_same_name() {
let src = build_solidity(
let wasm = build_solidity(
r#"contract math {
function max(uint64 a, uint64 b) public returns (uint64) {
if (a > b) {
Expand All @@ -38,7 +41,7 @@ fn math_same_name() {
return b;
}
}

function max(uint64 a, uint64 b, uint64 c) public returns (uint64) {
if (a > b) {
if (a > c) {
Expand All @@ -57,19 +60,21 @@ fn math_same_name() {
}
"#,
);

let addr = src.contracts.last().unwrap();
let mut src = SorobanEnv::new();
// No constructor arguments
let constructor_args: soroban_sdk::Vec<Val> = soroban_sdk::Vec::new(&src.env);
let address = src.register_contract(wasm, constructor_args);

let arg1: Val = 5_u64.into_val(&src.env);
let arg2: Val = 4_u64.into_val(&src.env);
let res = src.invoke_contract(addr, "max_uint64_uint64", vec![arg1, arg2]);
let res = src.invoke_contract(&address, "max_uint64_uint64", vec![arg1, arg2]);
let expected: Val = 5_u64.into_val(&src.env);
assert!(expected.shallow_eq(&res));

let arg1: Val = 5_u64.into_val(&src.env);
let arg2: Val = 4_u64.into_val(&src.env);
let arg3: Val = 6_u64.into_val(&src.env);
let res = src.invoke_contract(addr, "max_uint64_uint64_uint64", vec![arg1, arg2, arg3]);
let res = src.invoke_contract(&address, "max_uint64_uint64_uint64", vec![arg1, arg2, arg3]);
let expected: Val = 6_u64.into_val(&src.env);
assert!(expected.shallow_eq(&res));
}
1 change: 1 addition & 0 deletions tests/soroban_testcases/mod.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
// SPDX-License-Identifier: Apache-2.0
mod constructor;
mod math;
mod print;
mod storage;
Loading
Loading