1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
use std::env;
use std::sync::Arc;

use ethers::prelude::k256::ecdsa::SigningKey;
use ethers::prelude::{ContractCall, SignerMiddleware};
use ethers::providers::{Http, JsonRpcClient, Provider};
use ethers::signers::{Signer, Wallet};
use ethers::types::{Address, Bytes, H160, U256};
// use ethers::utils;
use switchboard_common::{
    ChainResultInfo, EVMFunctionResult, EvmTransaction, FunctionResult, Gramine,
};

use crate::bindings::error::SwitchboardClientError;
use crate::bindings::{eip712, switchboard};
use crate::utils::{generate_signer, load_env_address};
#[derive(Clone)]
pub struct EVMFunctionRunner {
    pub client: Provider<Http>,
    pub signing_wallet: Arc<Wallet<SigningKey>>,
    pub signer: Address,
    pub verifying_contract: Address,
    pub chain_id: u64,
}

impl std::fmt::Display for EVMFunctionRunner {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "SwitchboardFunctionRunner: url: {}, signer: {}, verifying_contract: {}",
            self.client.url(),
            self.signer,
            self.verifying_contract.to_string()
        )
    }
}
pub type EVMMiddleware<T> = SignerMiddleware<Provider<T>, Wallet<SigningKey>>;
pub type EVMContract<T> = switchboard::Switchboard<EVMMiddleware<T>>;

impl EVMFunctionRunner {
    pub fn new_with_client(client: Provider<Http>) -> Result<Self, SwitchboardClientError> {
        let signing_wallet = generate_signer();
        let signer = signing_wallet.address();

        let chain_id = env::var("CHAIN_ID")?;
        let verifying_contract = load_env_address("VERIFYING_CONTRACT")?;

        Ok(Self {
            client,
            signing_wallet,
            signer,
            verifying_contract,
            chain_id: chain_id.parse().unwrap_or(1),
        })
    }
    pub fn new(url: &str) -> Result<EVMFunctionRunner, SwitchboardClientError> {
        let signing_wallet = generate_signer();
        let client = Provider::<Http>::try_from(url).unwrap(); // temporary
        let signer = signing_wallet.address();
        let chain_id = env::var("CHAIN_ID")?;
        let verifying_contract = load_env_address("VERIFYING_CONTRACT")?;

        Ok(Self {
            client,
            signing_wallet,
            signer,
            verifying_contract,
            chain_id: chain_id.parse().unwrap_or(1),
        })
    }
    pub fn get_result<T: JsonRpcClient>(
        &self,
        contract: EVMContract<T>,
        expiration_time_seconds: U256,
        gas_limit: U256,
        calls: Vec<ContractCall<EVMMiddleware<T>, ()>>, // vector of instructions to call
    ) -> Result<FunctionResult, SwitchboardClientError> {
        let (evm_txns, signatures): (Vec<EvmTransaction>, Vec<Bytes>) = calls
            .iter()
            .map(|c| {
                // TODO: gas limit should be moved to function settings on-chain
                let transaction = switchboard::Transaction {
                    expiration_time_seconds,
                    gas_limit,
                    value: U256::from(0),
                    to: std::env::var("TARGET_CONTRACT").unwrap().parse().unwrap(),
                    from: self.signing_wallet.address(),
                    data: c.tx.data().unwrap().clone(),
                };

                let eip712_hash = eip712::get_transaction_hash(
                    "Switchboard".to_string(),
                    "0.0.1".to_string(),
                    self.chain_id,
                    contract.address(),
                    transaction,
                )
                .unwrap();

                let evm_txn = EvmTransaction {
                    expiration_time_seconds: expiration_time_seconds.as_u64(),
                    gas_limit: gas_limit.to_string(),
                    data: c.tx.data().unwrap().clone().to_vec(),
                    from: self.signing_wallet.address().as_bytes().to_vec(),
                    to: contract.address().as_bytes().to_vec(),
                    value: String::from("0"),
                };

                (
                    evm_txn,
                    Bytes::from(
                        self.signing_wallet
                            .sign_hash(ethers::types::H256::from(eip712_hash))
                            .unwrap()
                            .to_vec(),
                    ),
                )
            })
            .unzip();
        let chain_result_info = ChainResultInfo::Evm(EVMFunctionResult {
            txs: evm_txns.clone(),
            signatures: signatures.iter().map(|s| s.to_vec()).collect(),
        });
        let quote_raw =
            Gramine::generate_quote(&self.signing_wallet.signer().to_bytes()).unwrap_or_default();

        Ok(FunctionResult {
            version: 1,
            quote: quote_raw,
            fn_key: vec![],
            signer: self.signing_wallet.signer().to_bytes().to_vec(),
            fn_request_key: vec![],
            fn_request_hash: Vec::new(),
            chain_result_info,
        })
    }
    pub fn emit<T: JsonRpcClient>(
        &self,
        contract: EVMContract<T>,
        expiration_time_seconds: U256,
        gas_limit: U256,
        calls: Vec<ContractCall<EVMMiddleware<T>, ()>>, // vector of instructions to call
    ) -> Result<(), SwitchboardClientError> {
        self.get_result(contract, expiration_time_seconds, gas_limit, calls)
            .map_err(|e| SwitchboardClientError::CustomError {
                message: "failed to run function verify".to_string(),
                source: std::sync::Arc::new(e),
            })
            .unwrap()
            .emit();
        Ok(())
    }
}