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

chore: pull monorepo changes #11

Open
wants to merge 1 commit 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
3 changes: 2 additions & 1 deletion examples/01_randomness_callback/Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ FROM switchboardlabs/sgx-function AS builder

ARG CARGO_NAME=switchboard-function-evm
ENV CARGO_NAME=$CARGO_NAME
ENV EXAMPLE_PROGRAM=$EXAMPLE_PROGRAM

WORKDIR /home/root/switchboard-function
COPY switchboard-function/Cargo.toml ./Cargo.toml
Expand All @@ -25,4 +26,4 @@ RUN rm -f /measurement.txt && \
/get_measurement.sh && \
cat /measurement.txt

ENTRYPOINT ["bash", "/boot.sh"]
ENTRYPOINT ["bash", "/boot.sh"]
7 changes: 4 additions & 3 deletions examples/01_randomness_callback/Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -33,12 +33,13 @@ dev: dev_docker_build measurement
publish: docker_publish measurement

measurement:
@docker run -d --platform=linux/amd64 --pull always -q --name=my-switchboard-function ${DOCKER_IMAGE_NAME}:latest > /dev/null
@docker run -d --platform=linux/amd64 -q --name=my-switchboard-function ${DOCKER_IMAGE_NAME}:latest > /dev/null
@docker cp my-switchboard-function:/measurement.txt measurement.txt
@echo -n 'MrEnclve: '
@cat measurement.txt
@docker stop my-switchboard-function > /dev/null
@docker rm my-switchboard-function > /dev/null
@echo MrEnclave: $(shell cat ./measurement.txt)

# Task to clean up the compiled rust application
clean:
cargo clean
cargo clean
12 changes: 12 additions & 0 deletions examples/01_randomness_callback/hardhat.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,18 @@ const config: HardhatUserConfig = {
accounts:
process.env.PRIVATE_KEY !== undefined ? [process.env.PRIVATE_KEY] : [],
},
optimismTestnet: {
chainId: 420,
url: process.env.OPTIMISM_TESTNET_URL || "https://goerli.optimism.io",
accounts:
process.env.PRIVATE_KEY !== undefined ? [process.env.PRIVATE_KEY] : [],
},
optimismMain: {
chainId: 10,
url: process.env.OPTIMISM_MAINNET_URL || "https://mainnet.optimism.io",
accounts:
process.env.PRIVATE_KEY !== undefined ? [process.env.PRIVATE_KEY] : [],
},
},
};

Expand Down
8 changes: 4 additions & 4 deletions examples/01_randomness_callback/src/ReceiverExample.sol
Original file line number Diff line number Diff line change
Expand Up @@ -18,12 +18,12 @@ contract ReceiverExample is Recipient {

function callback(uint256 value) external {
// extract the sender from the callback, this validates that the switchboard contract called this function
address msgSender = getMsgSender();
// address msgSender = getMsgSender();

// make sure the encoded caller is our function id
if (msgSender != functionId) {
revert("Invalid sender");
}
// if (msgSender != functionId) {
// revert("Invalid sender");
// }

// set the random value
randomValue = value;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,4 +15,8 @@ futures = "0.3"
ethers = { version = "2.0.7", features = ["legacy"] }
rand = "0.8.5"
serde_json = "1.0.64"
switchboard-evm = "0.3.9"
base64 = "0.21.4"
chrono = "0.4.31"
num_enum = "0.7.1"
sb_macros = {path = "../../../../../rust/sb-macros"}
switchboard-evm = {path = "../../../../../rust/switchboard-evm"}
99 changes: 28 additions & 71 deletions examples/01_randomness_callback/switchboard-function/src/main.rs
Original file line number Diff line number Diff line change
@@ -1,71 +1,28 @@
use ethers::{
prelude::{abigen, SignerMiddleware, ContractCall},
providers::{Http, Provider},
types::{U256},
};
use rand;
use std::sync::Arc;
use std::time::{SystemTime, Duration};
use switchboard_evm::{
sdk::{EVMFunctionRunner, EVMMiddleware},
};


#[tokio::main(worker_threads = 12)]
async fn main() {

// define the abi for the functions in the contract you'll be calling
// -- here it's just a function named "callback", expecting a random u256
abigen!(
Receiver,
r#"[
function callback(uint256)
]"#,
);

// Generates a new enclave wallet, pulls in relevant environment variables
let function_runner = EVMFunctionRunner::new().unwrap();

// set the gas limit and expiration date
let gas_limit = 1000000;
let expiration_time_seconds = 60;
let current_time = SystemTime::now()
.duration_since(SystemTime::UNIX_EPOCH)
.unwrap_or(Duration::ZERO)
.as_secs() + 64;


// create a client, wallet and middleware. This is just so we can create the contract instance and sign the txn.
// @TODO: update the provider to whichever network you're using
let provider = Provider::<Http>::try_from("https://rpc.test.btcs.network").unwrap();
let client = Arc::new(
SignerMiddleware::new_with_provider_chain(provider.clone(), function_runner.enclave_wallet.clone())
.await
.unwrap(),
);

// @TODO: your target contract address here
let contract_address = "0x1cEA45f047FEa89887B79ce28723852f288eE09B"
.parse::<ethers::types::Address>()
.unwrap();
let receiver_contract = Receiver::new(contract_address, client);

// generate a random number U256
let random: [u64; 4] = rand::random();
let random = U256(random);

// call function
let contract_fn_call: ContractCall<EVMMiddleware<_>, _> =
receiver_contract.callback(random);

// create a vec of contract calls to pass to the function runner
let calls = vec![contract_fn_call.clone()];

// Emit the result
function_runner.emit(
contract_address,
current_time.try_into().unwrap(),
gas_limit.into(),
calls,
).unwrap();
}
use ethers::{prelude::{abigen, SignerMiddleware}, types::*};
use ethers::abi::AbiDecode;
use ethers::contract::{EthAbiType, EthAbiCodec};
use switchboard_evm::sdk::{EVMFunctionRunner};
use switchboard_evm::{Gramine, SbMiddleware, FnCall};
use sb_macros::{sb_function, sb_error};

abigen!(Receiver, r#"[function callback(uint256)]"#);

static CLIENT_URL: &str = "https://goerli-rollup.arbitrum.io/rpc";

#[derive(EthAbiType, EthAbiCodec, Default, Debug, Clone)]
pub struct Params {
callback: Address,
}

#[sb_function(expiration_seconds = 120, gas_limit = 5_500_000)]
async fn sb_function(client: SbMiddleware, _call_id: Address, params: Params) -> SbResult {
let receiver_contract = Receiver::new(params.callback, client.into());
let mut random = [0u8; 32];
Gramine::read_rand(random.as_mut_slice()).map_err(|_| SbError::SgxRandReadFail)?;
Ok(vec![receiver_contract.callback(U256::from_little_endian(&random))])
}

#[sb_error]
pub enum SbError {
SgxRandReadFail
}
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ const _abi = [
] as const;

const _bytecode =
"0x60a060405234801561001057600080fd5b5060405161026c38038061026c83398101604081905261002f91610073565b6001600160a01b03918216608052600180546001600160a01b031916919092161790556100a6565b80516001600160a01b038116811461006e57600080fd5b919050565b6000806040838503121561008657600080fd5b61008f83610057565b915061009d60208401610057565b90509250929050565b6080516101ab6100c1600039600061011501526101ab6000f3fe608060405234801561001057600080fd5b50600436106100365760003560e01c8063276801ec1461003b578063ff585caf14610056575b600080fd5b61004460005481565b60405190815260200160405180910390f35b61006961006436600461015c565b61006b565b005b6000610075610106565b6001549091506001600160a01b038083169116146100ca5760405162461bcd60e51b815260206004820152600e60248201526d24b73b30b634b21039b2b73232b960911b604482015260640160405180910390fd5b60008290556040518281527f13900022f509a2c2b75b4257430907a53c47c47b049f8a0a56b7a83e4e82f3999060200160405180910390a15050565b336014361080159061014957507f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316816001600160a01b0316145b15610159575060131936013560601c5b90565b60006020828403121561016e57600080fd5b503591905056fea264697066735822122017a1a72a06a719c25ed35b9330fd059e8ff2ee416a0f4fcef245c7445d719fa664736f6c63430008110033";
"0x60a060405234801561001057600080fd5b506040516101a73803806101a783398101604081905261002f91610073565b6001600160a01b03918216608052600180546001600160a01b031916919092161790556100a6565b80516001600160a01b038116811461006e57600080fd5b919050565b6000806040838503121561008657600080fd5b61008f83610057565b915061009d60208401610057565b90509250929050565b60805160eb6100bc6000396000505060eb6000f3fe6080604052348015600f57600080fd5b506004361060325760003560e01c8063276801ec146037578063ff585caf146051575b600080fd5b603f60005481565b60405190815260200160405180910390f35b6060605c366004609d565b6062565b005b60008190556040518181527f13900022f509a2c2b75b4257430907a53c47c47b049f8a0a56b7a83e4e82f3999060200160405180910390a150565b60006020828403121560ae57600080fd5b503591905056fea264697066735822122070889c73043e9bebbeebc1cfde415e2887888236a34edf9bb27a6261784cb36564736f6c63430008110033";

type ReceiverExampleConstructorParams =
| [signer?: Signer]
Expand Down
4 changes: 3 additions & 1 deletion examples/02_user_triggered_callback/Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ FROM switchboardlabs/sgx-function AS builder

ARG CARGO_NAME=switchboard-function-evm
ENV CARGO_NAME=$CARGO_NAME
ARG CALLBACK_ADDRESS
ENV CALLBACK_ADDRESS=$CALLBACK_ADDRESS

WORKDIR /home/root/switchboard-function
COPY switchboard-function/Cargo.toml ./Cargo.toml
Expand All @@ -25,4 +27,4 @@ RUN rm -f /measurement.txt && \
/get_measurement.sh && \
cat /measurement.txt

ENTRYPOINT ["bash", "/boot.sh"]
ENTRYPOINT ["bash", "/boot.sh"]
4 changes: 2 additions & 2 deletions examples/02_user_triggered_callback/Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
CARGO_NAME=evm-randomness-function
DOCKER_IMAGE_NAME=switchboardlabs/evm-randomness-function

DOCKER_BUILD_COMMAND=DOCKER_BUILDKIT=1 docker buildx build --platform linux/amd64 --build-arg CARGO_NAME=${CARGO_NAME}
DOCKER_BUILD_COMMAND=DOCKER_BUILDKIT=1 docker buildx build --platform linux/amd64 --build-arg CARGO_NAME=${CARGO_NAME} --build-arg CALLBACK_ADDRESS=${CALLBACK_ADDRESS}

# Default make task
all: build
Expand Down Expand Up @@ -41,4 +41,4 @@ measurement:

# Task to clean up the compiled rust application
clean:
cargo clean
cargo clean
Original file line number Diff line number Diff line change
Expand Up @@ -15,4 +15,7 @@ futures = "0.3"
ethers = { version = "2.0.7", features = ["legacy"] }
rand = "0.8.5"
serde_json = "1.0.64"
switchboard-evm = "0.3.9"
switchboard-evm = "0.4.15"
base64 = "0.21.4"
chrono = "0.4.31"
num_enum = "0.7.0"
146 changes: 56 additions & 90 deletions examples/02_user_triggered_callback/switchboard-function/src/main.rs
Original file line number Diff line number Diff line change
@@ -1,95 +1,61 @@
use ethers::abi::AbiDecode;
use ethers::{
prelude::{abigen, SignerMiddleware, ContractCall, EthAbiType, EthAbiCodec},
providers::{Http, Provider},
types::{U256, Address},
prelude::{abigen, EthAbiCodec, EthAbiType, SignerMiddleware},
providers::{Http, Provider},
types::{Address, U256},
};
use rand;
use std::sync::Arc;
use std::time::{SystemTime, Duration};
use switchboard_evm::{
sdk::{EVMFunctionRunner, EVMMiddleware},
};
use std::env;


#[tokio::main(worker_threads = 12)]
async fn main() {

// define the abi for the functions in the contract you'll be calling
// -- here it's just a function named "callback", expecting a random u256
abigen!(
Receiver,
r#"[
function fillOrder(uint256,uint256)
]"#,
);

#[derive(Debug, Clone, EthAbiType, EthAbiCodec)]
struct OrderParams {
orderId: U256,
sender: Address,
}

// Generates a new enclave wallet, pulls in relevant environment variables
let function_runner = EVMFunctionRunner::new().unwrap();

// set the gas limit and expiration date
let gas_limit = 1_000_000;
let current_time = SystemTime::now()
.duration_since(SystemTime::UNIX_EPOCH)
.unwrap_or(Duration::ZERO)
.as_secs() + 64;


// create a client, wallet and middleware. This is just so we can create the contract instance and sign the txn.
// @TODO: update the provider to whichever network you're using
let provider = Provider::<Http>::try_from("https://rpc.test.btcs.network").unwrap();
let client = Arc::new(
SignerMiddleware::new_with_provider_chain(provider.clone(), function_runner.enclave_wallet.clone())
.await
.unwrap(),
);

// @TODO: your target contract address here
let contract_address = "0x8610Eac76946A5c724f840a790f39777a4aa0770"
.parse::<ethers::types::Address>()
.unwrap();
let receiver_contract = Receiver::new(contract_address, client);

// Get individual call parameters
let params = function_runner.params::<OrderParams>();


// log envvars
let call_ids = env::var("FUNCTION_CALL_IDS").unwrap_or(String::new());

// print call_ids
println!("Received call ids: {}", call_ids);

let call_ids: Vec<Vec<u8>> = serde_json::from_str(&call_ids).unwrap_or(vec![]);

// Handle each function call that has happened since the last run
let calls: Vec<ContractCall<EVMMiddleware<_>, _>> = params.iter().map(|param| {
let order_id = param.orderId;
let sender = param.sender;

println!("Received order {} from {}", order_id, sender);

// generate a random number U256
let random: [u64; 4] = rand::random();
let random = U256(random);

// Create a contract call for each param
let contract_fn_call: ContractCall<EVMMiddleware<_>, _> =
receiver_contract.fill_order(order_id, random);
contract_fn_call
}).collect::<Vec<_>>();
use ethers::prelude::*;
use switchboard_evm::sb_error;
use switchboard_evm::sb_function;
use switchboard_evm::sdk::EVMFunctionRunner;
use switchboard_evm::FnCall;
use switchboard_evm::SbFunctionParameters;

/// REQUIRED
static CLIENT_URL: &str = "https://goerli-rollup.arbitrum.io/rpc";
static RECEIVER: &str = env!("CALLBACK_ADDRESS");

// define the abi for the functions in the contract you'll be calling
// -- here it's just a function named "callback", expecting a random u256
abigen!(Receiver, r#"[function fillOrder(uint256,uint256)]"#);

#[derive(Default, Debug, Clone, EthAbiType, EthAbiCodec)]
struct OrderParams {
orderId: U256,
sender: Address,
}
impl SbFunctionParameters for OrderParams {
fn parse(data: &[u8]) -> Self {
OrderParams::decode(data).unwrap_or_default()
}
}

#[sb_function(expiration_seconds = 120, gas_limit = 5_500_000)]
async fn sb_function<M: Middleware, S: Signer>(
client: SignerMiddleware<M, S>,
params: OrderParams,
) -> Result<Vec<FnCall<M, S>>, Error> {
let contract_address: Address = RECEIVER.parse().map_err(|_| Error::ParseError)?;
let receiver_contract = Receiver::new(contract_address, client.into());

let order_id = params.orderId;
let sender = params.sender;

println!("Received order {} from {}", order_id, sender);

// generate a random number U256
let random: [u64; 4] = rand::random();
let random = U256(random);

// Create a contract call for each param
let contract_fn_call = receiver_contract.fill_order(order_id, random);
Ok(vec![contract_fn_call])
}

#[sb_error]
enum Error {
ParseError = 1,
}

// Emit the result
function_runner.emit(
contract_address,
current_time.try_into().unwrap(),
gas_limit.into(),
calls,
).unwrap();
}
Loading
Loading