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
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
//! CustomAccount provides access to helper functions for custom account
//! contracts.
//!
//! The accessor can be created using [Env::custom_account].
//!
//! ### Examples
//!
//! A modular custom account that performs authentication by delegating to
//! other accounts instead of doing the authentication itself. The user
//! chooses which of the registered signers to authenticate with, by
//! attaching them to the transaction as delegated signers.
//!
//! ```
//! use soroban_sdk::{
//! auth::{Context, CustomAccountInterface},
//! contract, contracterror, contractimpl, contracttype,
//! crypto::Hash, vec, Address, Env, Vec,
//! };
//!
//! #[contracterror]
//! #[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord)]
//! #[repr(u32)]
//! pub enum Error {
//! UnknownDelegate = 1,
//! }
//!
//! #[contracttype]
//! enum ModularAccountDataKey {
//! // Marks an address as a signer allowed to authenticate for the
//! // modular account.
//! Signer(Address),
//! }
//!
//! #[contract]
//! pub struct ModularAccount;
//!
//! #[contractimpl]
//! impl ModularAccount {
//! // Registers the addresses allowed to authenticate for this account.
//! pub fn __constructor(env: Env, signers: Vec<Address>) {
//! for signer in signers.iter() {
//! env.storage()
//! .persistent()
//! .set(&ModularAccountDataKey::Signer(signer), &());
//! }
//! }
//! }
//!
//! #[contractimpl]
//! impl CustomAccountInterface for ModularAccount {
//! // The account verifies no signature of its own, so it carries no
//! // signature to check.
//! type Signature = ();
//! type Error = Error;
//!
//! fn __check_auth(
//! env: Env,
//! _signature_payload: Hash<32>,
//! _signatures: (),
//! _auth_contexts: Vec<Context>,
//! ) -> Result<(), Error> {
//! // The signers the user attached to the auth entry for this
//! // account's authorization.
//! let delegates = env.custom_account().get_delegated_signers();
//!
//! // Check if the delegates are accepted by the modular account.
//! for delegate in delegates.iter() {
//! if !env
//! .storage()
//! .persistent()
//! .has(&ModularAccountDataKey::Signer(delegate.clone()))
//! {
//! return Err(Error::UnknownDelegate);
//! }
//! }
//! // Forward the current authorization to each delegate.
//! for delegate in delegates.iter() {
//! env.custom_account().delegate_auth(&delegate);
//! }
//! Ok(())
//! }
//! }
//!
//! #[contracttype]
//! enum DelegateAccountDataKey {
//! // Records the contexts the delegate approved so the test can verify
//! // the delegation reached it.
//! ApprovedContexts,
//! }
//!
//! // A simple account that the ModularAccount can delegate to for auth.
//! //
//! // It will always authorize an auth request, and store a copy of the auth
//! // context for later comparing in tests.
//! #[contract]
//! pub struct DelegateAccount;
//!
//! #[contractimpl]
//! impl CustomAccountInterface for DelegateAccount {
//! type Signature = ();
//! type Error = Error;
//! fn __check_auth(
//! env: Env,
//! _signature_payload: Hash<32>,
//! _signatures: (),
//! auth_contexts: Vec<Context>,
//! ) -> Result<(), Error> {
//! env.storage()
//! .instance()
//! .set(&DelegateAccountDataKey::ApprovedContexts, &auth_contexts);
//! // Returning `Ok(())` approves the auth;
//! // returning an error would reject it.
//! Ok(())
//! }
//! }
//!
//! // A contract with an operation that requires the account's authorization.
//! #[contract]
//! pub struct Protected;
//!
//! #[contractimpl]
//! impl Protected {
//! pub fn protected(account: Address) {
//! account.require_auth();
//! }
//! }
//!
//! #[test]
//! fn test() {
//! # }
//! # #[cfg(feature = "testutils")]
//! # fn main() {
//! use soroban_sdk::{
//! auth::ContractContext,
//! testutils::{AuthorizedFunction, AuthorizedInvocation},
//! xdr::{
//! InvokeContractArgs, ScAddress, ScVal, SorobanAddressCredentials,
//! SorobanAddressCredentialsWithDelegates, SorobanAuthorizationEntry,
//! SorobanAuthorizedFunction, SorobanAuthorizedInvocation,
//! SorobanCredentials, SorobanDelegateSignature, StringM, VecM,
//! },
//! IntoVal, Symbol,
//! };
//!
//! let env = Env::default();
//! let delegate = env.register(DelegateAccount, ());
//! // Register the modular account with `delegate` as an allowed signer.
//! let account = env.register(ModularAccount, (vec![&env, delegate.clone()],));
//! let protected = env.register(Protected, ());
//!
//! let account_addr: ScAddress = account.clone().try_into().unwrap();
//! let delegate_addr: ScAddress = delegate.clone().try_into().unwrap();
//!
//! // This authorization entry is normally built by the user's
//! // wallet/tooling and attached to the transaction. It authorizes
//! // `protected` on behalf of the account, and attaches `delegate` as a
//! // delegated signer. Delegates must be sorted by address with no
//! // duplicates.
//! env.set_auths(&[SorobanAuthorizationEntry {
//! credentials: SorobanCredentials::AddressWithDelegates(
//! SorobanAddressCredentialsWithDelegates {
//! address_credentials: SorobanAddressCredentials {
//! address: account_addr.clone(),
//! nonce: 1,
//! signature_expiration_ledger: 100,
//! // The account verifies no signature of its own.
//! signature: ScVal::Void,
//! },
//! delegates: std::vec![SorobanDelegateSignature {
//! address: delegate_addr,
//! signature: ScVal::Void,
//! nested_delegates: VecM::default(),
//! }]
//! .try_into()
//! .unwrap(),
//! },
//! ),
//! root_invocation: SorobanAuthorizedInvocation {
//! function: SorobanAuthorizedFunction::ContractFn(InvokeContractArgs {
//! contract_address: protected.clone().try_into().unwrap(),
//! function_name: StringM::try_from("protected").unwrap().into(),
//! args: std::vec![ScVal::Address(account_addr)].try_into().unwrap(),
//! }),
//! sub_invocations: VecM::default(),
//! },
//! }]);
//!
//! // The call succeeds: the account delegates its authentication to
//! // `delegate`, which approves it.
//! ProtectedClient::new(&env, &protected).protected(&account);
//!
//! // The account authorized the `protected` call. Delegating to
//! // `delegate` is not recorded as a separate authorization.
//! assert_eq!(
//! env.auths(),
//! std::vec![(
//! account.clone(),
//! AuthorizedInvocation {
//! function: AuthorizedFunction::Contract((
//! protected.clone(),
//! Symbol::new(&env, "protected"),
//! (account.clone(),).into_val(&env),
//! )),
//! sub_invocations: std::vec![],
//! }
//! )]
//! );
//!
//! // The delegation actually reached `delegate`, which approved the
//! // same invocation that was authorized above.
//! let approved: Vec<Context> = env.as_contract(&delegate, || {
//! env.storage()
//! .instance()
//! .get(&DelegateAccountDataKey::ApprovedContexts)
//! .unwrap()
//! });
//! assert_eq!(
//! approved,
//! vec![
//! &env,
//! Context::Contract(ContractContext {
//! contract: protected.clone(),
//! fn_name: Symbol::new(&env, "protected"),
//! args: (account.clone(),).into_val(&env),
//! }),
//! ],
//! );
//! }
//! # #[cfg(not(feature = "testutils"))]
//! # fn main() { }
//! ```
use crate::;
/// Provides access to functions used for custom account implementation.
///
/// The accessor's methods may only be called within `__check_auth` contract
/// function.