-
Notifications
You must be signed in to change notification settings - Fork 477
Expand file tree
/
Copy pathapi.rs
More file actions
1089 lines (1027 loc) · 34 KB
/
api.rs
File metadata and controls
1089 lines (1027 loc) · 34 KB
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
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (C) Use Ink (UK) Ltd.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! The public raw interface towards the host engine.
#[cfg(feature = "xcm")]
use ink_primitives::Weight;
use ink_primitives::{
Address,
CodeHashErr,
H256,
U256,
abi::{
Ink,
Sol,
},
sol::SolResultEncode,
};
use ink_storage_traits::Storable;
use pallet_revive_uapi::ReturnFlags;
use crate::{
DecodeDispatch,
DispatchError,
Result,
backend::{
EnvBackend,
TypedEnvBackend,
},
call::{
Call,
CallParams,
ConstructorReturnType,
CreateParams,
DelegateCall,
FromAddr,
LimitParamsV2,
utils::{
DecodeMessageResult,
EncodeArgsWith,
},
},
engine::{
EnvInstance,
OnInstance,
},
event::Event,
hash::{
CryptoHash,
HashOutput,
},
types::{
Environment,
Gas,
},
};
/// Returns the address of the caller of the executed contract.
///
/// # Errors
///
/// If the returned caller cannot be properly decoded.
pub fn caller() -> Address {
<EnvInstance as OnInstance>::on_instance(TypedEnvBackend::caller)
}
/// Returns the block's `ref_time` limit.
/// [GASLIMIT](https://www.evm.codes/?fork=cancun#45) opcode.
///
/// See <https://use.ink/docs/v6/basics/gas/#what-is-gas-in-ink> for more information.
pub fn gas_limit() -> u64 {
<EnvInstance as OnInstance>::on_instance(TypedEnvBackend::gas_limit)
}
/// Returns the price per `ref_time`, akin to the EVM
/// [GASPRICE](https://www.evm.codes/?fork=cancun#3a) opcode.
///
/// See <https://use.ink/docs/v6/basics/gas/#what-is-gas-in-ink> for more information.
pub fn gas_price() -> u64 {
<EnvInstance as OnInstance>::on_instance(TypedEnvBackend::gas_price)
}
/// Returns the amount of gas left.
/// This is the `ref_time` left.
///
/// See <https://use.ink/docs/v6/basics/gas/#what-is-gas-in-ink> for more information.
pub fn gas_left() -> u64 {
<EnvInstance as OnInstance>::on_instance(TypedEnvBackend::gas_left)
}
/// Returns the total size of the contract call input data, akin to the EVM
/// [CALLDATASIZE](https://www.evm.codes/?fork=cancun#36) opcode.
pub fn call_data_size() -> u64 {
<EnvInstance as OnInstance>::on_instance(TypedEnvBackend::call_data_size)
}
/// Returns the size of the returned data of the last contract call or instantiation,
/// akin to the EVM [RETURNDATASIZE](https://www.evm.codes/?fork=cancun#3d) opcode.
pub fn return_data_size() -> u64 {
<EnvInstance as OnInstance>::on_instance(TypedEnvBackend::return_data_size)
}
/// Returns the [EIP-155](https://eips.ethereum.org/EIPS/eip-155) chain ID,
/// akin to the EVM [CHAINID](https://www.evm.codes/?fork=cancun#46) opcode.
pub fn chain_id() -> U256 {
<EnvInstance as OnInstance>::on_instance(TypedEnvBackend::chain_id)
}
/// Returns the **reducible** native balance of the supplied address,
/// akin to the EVM [BALANCE](https://www.evm.codes/?fork=cancun#31) opcode.
pub fn balance_of(addr: Address) -> U256 {
<EnvInstance as OnInstance>::on_instance(|instance| {
TypedEnvBackend::balance_of(instance, addr)
})
}
/// Returns the base fee.
/// This is akin to the EVM [BASEFEE](https://www.evm.codes/?fork=cancun#48) opcode.
pub fn base_fee() -> U256 {
<EnvInstance as OnInstance>::on_instance(TypedEnvBackend::base_fee)
}
/// Returns the origin address (initiator of the call stack).
/// This is akin to the EVM [ORIGIN](https://www.evm.codes/?fork=cancun#32) opcode.
///
/// # Errors
///
/// - If there is no address associated with the origin (e.g. because the origin is root).
pub fn origin() -> Address {
<EnvInstance as OnInstance>::on_instance(TypedEnvBackend::origin)
}
/// Returns the code size for a specified contract address.
/// This is akin to the EVM [CODESIZE](https://www.evm.codes/?fork=cancun#38) opcode.
///
/// # Note
///
/// If `addr` is not a contract the `output` will be zero.
pub fn code_size(addr: Address) -> u64 {
<EnvInstance as OnInstance>::on_instance(|instance| {
TypedEnvBackend::code_size(instance, addr)
})
}
/// Returns the block hash of the given block number.
/// This is akin to the EVM [BLOCKHASH](https://www.evm.codes/?fork=cancun#40) opcode.
pub fn block_hash<E>(block_number: E::BlockNumber) -> H256
where
E: Environment,
{
<EnvInstance as OnInstance>::on_instance(|instance| {
TypedEnvBackend::block_hash::<E>(instance, block_number)
})
}
/// Returns the current block author.
/// This is akin to the EVM [COINBASE](https://www.evm.codes/?fork=cancun#41) opcode.
pub fn block_author() -> Address {
<EnvInstance as OnInstance>::on_instance(TypedEnvBackend::block_author)
}
/// Returns the transferred value for the contract execution.
///
/// # Errors
///
/// If the returned value cannot be properly decoded.
pub fn transferred_value() -> U256 {
<EnvInstance as OnInstance>::on_instance(|instance| {
TypedEnvBackend::transferred_value(instance)
})
}
/// Returns the price for the specified amount of gas.
///
/// # Errors
///
/// If the returned value cannot be properly decoded.
pub fn weight_to_fee(gas: Gas) -> U256 {
<EnvInstance as OnInstance>::on_instance(|instance| {
TypedEnvBackend::weight_to_fee(instance, gas)
})
}
/// Returns the current block timestamp.
///
/// # Errors
///
/// If the returned value cannot be properly decoded.
pub fn block_timestamp<E>() -> E::Timestamp
where
E: Environment,
{
<EnvInstance as OnInstance>::on_instance(|instance| {
TypedEnvBackend::block_timestamp::<E>(instance)
})
}
/// Retrieves the account id for a specified address.
///
/// # Errors
///
/// If the returned value cannot be properly decoded.
pub fn to_account_id<E>(addr: Address) -> E::AccountId
where
E: Environment,
{
<EnvInstance as OnInstance>::on_instance(|instance| {
TypedEnvBackend::to_account_id::<E>(instance, addr)
})
}
/// Returns the account ID of the executed contract.
///
/// # Note
///
/// This method was formerly known as `address`.
///
/// # Errors
///
/// If the returned value cannot be properly decoded.
pub fn account_id<E>() -> E::AccountId
where
E: Environment,
{
<EnvInstance as OnInstance>::on_instance(|instance| {
TypedEnvBackend::account_id::<E>(instance)
})
}
/// Returns the address of the executed contract.
///
/// # Errors
///
/// If the returned value cannot be properly decoded.
pub fn address() -> Address {
<EnvInstance as OnInstance>::on_instance(|instance| {
TypedEnvBackend::address(instance)
})
}
/// Returns the balance of the executed contract.
///
/// # Errors
///
/// If the returned value cannot be properly decoded.
pub fn balance() -> U256 {
<EnvInstance as OnInstance>::on_instance(|instance| {
TypedEnvBackend::balance(instance)
})
}
/// Returns the current block number.
///
/// # Errors
///
/// If the returned value cannot be properly decoded.
pub fn block_number<E>() -> E::BlockNumber
where
E: Environment,
{
<EnvInstance as OnInstance>::on_instance(|instance| {
TypedEnvBackend::block_number::<E>(instance)
})
}
/// Returns the minimum balance that is required for creating an account
/// (i.e. the chain's existential deposit).
///
/// # Errors
///
/// If the returned value cannot be properly decoded.
pub fn minimum_balance() -> U256 {
<EnvInstance as OnInstance>::on_instance(|instance| {
TypedEnvBackend::minimum_balance(instance)
})
}
/// Emits an event with the given event data.
///
/// # Note
///
/// In "all" ABI mode, both an ink! and Solidity ABI event are emitted.
#[cfg(not(ink_abi = "all"))]
pub fn emit_event<Evt>(event: Evt)
where
Evt: Event<crate::DefaultAbi>,
{
<EnvInstance as OnInstance>::on_instance(|instance| {
TypedEnvBackend::emit_event::<Evt, crate::DefaultAbi>(instance, &event)
})
}
/// Emits an event with the given event data.
///
/// # Note
///
/// In "all" ABI mode, both an ink! and Solidity ABI event are emitted.
#[cfg(ink_abi = "all")]
pub fn emit_event<Evt>(event: Evt)
where
Evt: Event<Ink> + Event<Sol>,
{
// Emits ink! ABI encoded event.
<EnvInstance as OnInstance>::on_instance(|instance| {
TypedEnvBackend::emit_event::<Evt, Ink>(instance, &event)
});
// Emits Solidity ABI encoded event.
<EnvInstance as OnInstance>::on_instance(|instance| {
TypedEnvBackend::emit_event::<Evt, Sol>(instance, &event)
});
}
/// Emits an event with the given event data using the ink! ABI encoding (i.e. with SCALE
/// codec for event data encode/decode).
pub fn emit_event_ink<Evt>(event: Evt)
where
Evt: Event<Ink>,
{
<EnvInstance as OnInstance>::on_instance(|instance| {
TypedEnvBackend::emit_event::<Evt, Ink>(instance, &event)
})
}
/// Emits an event with the given event data using the Solidity ABI encoding.
pub fn emit_event_sol<Evt>(event: Evt)
where
Evt: Event<Sol>,
{
<EnvInstance as OnInstance>::on_instance(|instance| {
TypedEnvBackend::emit_event::<Evt, Sol>(instance, &event)
})
}
/// Writes the value to the contract storage under the given storage key and returns the
/// size of pre-existing value if any.
///
/// # Panics
///
/// - If the encode length of value exceeds the configured maximum value length of a
/// storage entry.
pub fn set_contract_storage<K, V>(key: &K, value: &V) -> Option<u32>
where
K: scale::Encode,
V: Storable,
{
<EnvInstance as OnInstance>::on_instance(|instance| {
EnvBackend::set_contract_storage::<K, V>(instance, key, value)
})
}
/// Returns the value stored under the given storage key in the contract's storage if any.
///
/// # Errors
///
/// - If the decoding of the typed value failed (`KeyNotFound`)
pub fn get_contract_storage<K, R>(key: &K) -> Result<Option<R>>
where
K: scale::Encode,
R: Storable,
{
<EnvInstance as OnInstance>::on_instance(|instance| {
EnvBackend::get_contract_storage::<K, R>(instance, key)
})
}
/// Removes the `value` at `key`, returning the previous `value` at `key` from storage.
///
/// # Errors
///
/// - If the decoding of the typed value failed (`KeyNotFound`)
pub fn take_contract_storage<K, R>(key: &K) -> Result<Option<R>>
where
K: scale::Encode,
R: Storable,
{
<EnvInstance as OnInstance>::on_instance(|instance| {
EnvBackend::take_contract_storage::<K, R>(instance, key)
})
}
/// Checks whether there is a value stored under the given storage key in the contract's
/// storage.
///
/// If a value is stored under the specified key, the size of the value is returned.
pub fn contains_contract_storage<K>(key: &K) -> Option<u32>
where
K: scale::Encode,
{
<EnvInstance as OnInstance>::on_instance(|instance| {
EnvBackend::contains_contract_storage::<K>(instance, key)
})
}
/// Clears the contract's storage entry under the given storage key.
///
/// If a value was stored under the specified storage key, the size of the value is
/// returned.
pub fn clear_contract_storage<K>(key: &K) -> Option<u32>
where
K: scale::Encode,
{
<EnvInstance as OnInstance>::on_instance(|instance| {
EnvBackend::clear_contract_storage::<K>(instance, key)
})
}
/// Invokes a contract message and returns its result.
///
/// # Note
///
/// **This will call into the latest version of the host function which allows setting new
/// weight and storage limit parameters.**
///
/// This is a low level way to evaluate another smart contract.
/// Prefer to use the ink! guided and type safe approach to using this.
///
/// # Errors
///
/// - If the called account does not exist.
/// - If the called account is not a contract.
/// - If arguments passed to the called contract message are invalid.
/// - If the called contract execution has trapped.
/// - If the called contract ran out of gas, proof size, or storage deposit upon
/// execution.
/// - If the returned value failed to decode properly.
pub fn invoke_contract<E, Args, R, Abi>(
params: &CallParams<E, Call, Args, R, Abi>,
) -> Result<ink_primitives::MessageResult<R>>
where
E: Environment,
Args: EncodeArgsWith<Abi>,
R: DecodeMessageResult<Abi>,
{
<EnvInstance as OnInstance>::on_instance(|instance| {
TypedEnvBackend::invoke_contract::<E, Args, R, Abi>(instance, params)
})
}
/// Invokes a contract message via delegate call and returns its result.
///
/// # Note
///
/// This is a low level way to evaluate another smart contract via delegate call.
/// Prefer to use the ink! guided and type safe approach to using this.
///
/// # Errors
///
/// - If the specified code hash does not exist.
/// - If arguments passed to the called code message are invalid.
/// - If the called code execution has trapped.
pub fn invoke_contract_delegate<E, Args, R, Abi>(
params: &CallParams<E, DelegateCall, Args, R, Abi>,
) -> Result<ink_primitives::MessageResult<R>>
where
E: Environment,
Args: EncodeArgsWith<Abi>,
R: DecodeMessageResult<Abi>,
{
<EnvInstance as OnInstance>::on_instance(|instance| {
TypedEnvBackend::invoke_contract_delegate::<E, Args, R, Abi>(instance, params)
})
}
/// Instantiates another contract.
///
/// # Note
///
/// This is a low level way to instantiate another smart contract, calling the latest
/// `instantiate_v2` host function. // todo
///
/// Prefer to use methods on a `ContractRef` or the
/// [`CreateBuilder`](`crate::call::CreateBuilder`)
/// through [`build_create`](`crate::call::build_create`) instead.
///
/// # Errors
///
/// - If the code hash is invalid.
/// - If the arguments passed to the instantiation process are invalid.
/// - If the instantiation process traps.
/// - If the instantiation process runs out of gas.
/// - If given insufficient endowment.
/// - If the returned account ID failed to decode properly.
pub fn instantiate_contract<E, ContractRef, Args, R, Abi>(
params: &CreateParams<E, ContractRef, LimitParamsV2, Args, R, Abi>,
) -> Result<
ink_primitives::ConstructorResult<
<R as ConstructorReturnType<ContractRef, Abi>>::Output,
>,
>
where
E: Environment,
ContractRef: FromAddr + crate::ContractReverseReference,
<ContractRef as crate::ContractReverseReference>::Type:
crate::reflect::ContractConstructorDecoder,
Args: EncodeArgsWith<Abi>,
R: ConstructorReturnType<ContractRef, Abi>,
{
<EnvInstance as OnInstance>::on_instance(|instance| {
TypedEnvBackend::instantiate_contract::<E, ContractRef, Args, R, Abi>(
instance, params,
)
})
}
/// Terminates the existence of the currently executed smart contract.
///
/// This removes the calling account and transfers all remaining balance
/// to the given beneficiary.
///
/// # Note
///
/// This function never returns. Either the termination was successful and the
/// execution of the destroyed contract is halted. Or it failed during the termination
/// which is considered fatal and results in a trap and rollback.
#[cfg(feature = "unstable-hostfn")]
pub fn terminate_contract(beneficiary: Address) -> ! {
<EnvInstance as OnInstance>::on_instance(|instance| {
TypedEnvBackend::terminate_contract(instance, beneficiary)
})
}
/// Transfers value from the contract to the destination account ID.
///
/// # Note
///
/// This is more efficient and simpler than the alternative to make a no-op
/// contract call or invoke a runtime function that performs the
/// transaction.
///
/// # Errors
///
/// - If the contract does not have sufficient free funds.
/// - If the transfer had brought the sender's total balance below the minimum balance.
/// You need to use `terminate_contract` in case this is your intention.
pub fn transfer<E>(destination: Address, value: U256) -> Result<()>
where
E: Environment,
{
<EnvInstance as OnInstance>::on_instance(|instance| {
TypedEnvBackend::transfer::<E>(instance, destination, value)
})
}
/// Returns the execution input to the executed contract and decodes it as `T`.
///
/// # Note
///
/// - The input is the 4-bytes selector followed by the arguments of the called function
/// in their SCALE encoded representation.
/// - No prior interaction with the environment must take place before calling this
/// procedure.
///
/// # Usage
///
/// Normally contracts define their own `enum` dispatch types respective
/// to their exported constructors and messages that implement `scale::Decode`
/// according to the constructors or messages selectors and their arguments.
/// These `enum` dispatch types are then given to this procedure as the `T`.
///
/// When using ink! users do not have to construct those enum dispatch types
/// themselves as they are normally generated by the ink! code generation
/// automatically.
///
/// # Errors
///
/// If the given `T` cannot be properly decoded from the expected input.
pub fn decode_input<T>() -> core::result::Result<T, DispatchError>
where
T: DecodeDispatch,
{
<EnvInstance as OnInstance>::on_instance(|instance| {
EnvBackend::decode_input::<T>(instance)
})
}
/// Returns the value back to the caller of the executed contract.
///
/// # Note
///
/// This function stops the execution of the contract immediately.
#[cfg(not(feature = "std"))]
pub fn return_value<R>(return_flags: ReturnFlags, return_value: &R) -> !
where
R: scale::Encode,
{
<EnvInstance as OnInstance>::on_instance(|instance| {
EnvBackend::return_value::<R>(instance, return_flags, return_value)
})
}
/// Returns the value back to the caller of the executed contract.
///
/// # Note
///
/// When the `std` feature is used, the contract is allowed to
/// return normally. This feature should only be used for integration tests.
#[cfg(feature = "std")]
pub fn return_value<R>(return_flags: ReturnFlags, return_value: &R)
where
R: scale::Encode,
{
<EnvInstance as OnInstance>::on_instance(|instance| {
EnvBackend::return_value::<R>(instance, return_flags, return_value)
})
}
/// Returns the *Solidity ABI encoded* value back to the caller of the executed contract.
///
/// # Note
///
/// This function stops the execution of the contract immediately.
pub fn return_value_solidity<R>(return_flags: ReturnFlags, return_value: &R) -> !
where
R: for<'a> SolResultEncode<'a>,
{
<EnvInstance as OnInstance>::on_instance(|instance| {
EnvBackend::return_value_solidity::<R>(instance, return_flags, return_value)
})
}
/// Conducts the crypto hash of the given input and stores the result in `output`.
///
/// # Example
///
/// ```
/// use ink_env::hash::{
/// HashOutput,
/// Sha2x256,
/// };
/// let input: &[u8] = &[13, 14, 15];
/// let mut output = <Sha2x256 as HashOutput>::Type::default(); // 256-bit buffer
/// let hash = ink_env::hash_bytes::<Sha2x256>(input, &mut output);
/// ```
pub fn hash_bytes<H>(input: &[u8], output: &mut <H as HashOutput>::Type)
where
H: CryptoHash,
{
<EnvInstance as OnInstance>::on_instance(|instance| {
instance.hash_bytes::<H>(input, output)
})
}
/// Conducts the crypto hash of the given encoded input and stores the result in `output`.
///
/// # Example
///
/// ```
/// # use ink_env::hash::{Sha2x256, HashOutput};
/// const EXPECTED: [u8; 32] = [
/// 243, 242, 58, 110, 205, 68, 100, 244, 187, 55, 188, 248, 29, 136, 145, 115, 186,
/// 134, 14, 175, 178, 99, 183, 21, 4, 94, 92, 69, 199, 207, 241, 179,
/// ];
/// let encodable = (42, "foo", true); // Implements `scale::Encode`
/// let mut output = <Sha2x256 as HashOutput>::Type::default(); // 256-bit buffer
/// ink_env::hash_encoded::<Sha2x256, _>(&encodable, &mut output);
/// assert_eq!(output, EXPECTED);
/// ```
pub fn hash_encoded<H, T>(input: &T, output: &mut <H as HashOutput>::Type)
where
H: CryptoHash,
T: scale::Encode,
{
<EnvInstance as OnInstance>::on_instance(|instance| {
instance.hash_encoded::<H, T>(input, output)
})
}
/// Calls the `bn128_add` G1 addition precompile.
///
/// Inputs are affine G1 coordinates over Fq.
/// Returns the resulting affine point or (0, 0) if the result is ∞ / invalid.
///
/// # Note
///
/// The precompile address is `0x06`. You can find its implementation here:
/// <https://github.com/paritytech/polkadot-sdk/blob/master/substrate/frame/revive/src/precompiles/builtin/bn128.rs>
pub fn bn128_add(x1: U256, y1: U256, x2: U256, y2: U256) -> (U256, U256) {
<EnvInstance as OnInstance>::on_instance(|instance| {
instance.bn128_add(x1, y1, x2, y2)
})
}
/// Calls the `bn128_mul` G1 scalar-mul precompile.
///
/// Multiplies an affine G1 point (x1, y1) by a scalar ∈ Fr.
/// Returns the resulting affine point or (0, 0) if the result is ∞ / invalid.
///
/// # Note
///
/// The precompile address is `0x07`. You can find its implementation here:
/// <https://github.com/paritytech/polkadot-sdk/blob/master/substrate/frame/revive/src/precompiles/builtin/bn128.rs>
pub fn bn128_mul(x1: U256, y1: U256, scalar: U256) -> (U256, U256) {
<EnvInstance as OnInstance>::on_instance(|instance| {
instance.bn128_mul(x1, y1, scalar)
})
}
/// Calls the `bn128_pairing` precompile.
///
/// Input is the Solidity-ABI-encoded sequence of (G1, G2) pairs.
/// Returns `true` iff the product of pairings evaluates to the identity.
///
/// # Note
///
/// The precompile address is `0x08`. You can find its implementation here:
/// <https://github.com/paritytech/polkadot-sdk/blob/master/substrate/frame/revive/src/precompiles/builtin/bn128.rs>
pub fn bn128_pairing(input: &[u8]) -> bool {
<EnvInstance as OnInstance>::on_instance(|instance| instance.bn128_pairing(input))
}
/// Recovers the compressed ECDSA public key for given `signature` and `message_hash`,
/// and stores the result in `output`.
///
/// # Example
///
/// ```
/// const signature: [u8; 65] = [
/// 195, 218, 227, 165, 226, 17, 25, 160, 37, 92, 142, 238, 4, 41, 244, 211, 18, 94,
/// 131, 116, 231, 116, 255, 164, 252, 248, 85, 233, 173, 225, 26, 185, 119, 235,
/// 137, 35, 204, 251, 134, 131, 186, 215, 76, 112, 17, 192, 114, 243, 102, 166, 176,
/// 140, 180, 124, 213, 102, 117, 212, 89, 89, 92, 209, 116, 17, 28,
/// ];
/// const message_hash: [u8; 32] = [
/// 167, 124, 116, 195, 220, 156, 244, 20, 243, 69, 1, 98, 189, 205, 79, 108, 213,
/// 78, 65, 65, 230, 30, 17, 37, 184, 220, 237, 135, 1, 209, 101, 229,
/// ];
/// const EXPECTED_COMPRESSED_PUBLIC_KEY: [u8; 33] = [
/// 3, 110, 192, 35, 209, 24, 189, 55, 218, 250, 100, 89, 40, 76, 222, 208, 202, 127,
/// 31, 13, 58, 51, 242, 179, 13, 63, 19, 22, 252, 164, 226, 248, 98,
/// ];
/// let mut output = [0; 33];
/// ink_env::ecdsa_recover(&signature, &message_hash, &mut output);
/// assert_eq!(output, EXPECTED_COMPRESSED_PUBLIC_KEY);
/// ```
pub fn ecdsa_recover(
signature: &[u8; 65],
message_hash: &[u8; 32],
output: &mut [u8; 33],
) -> Result<()> {
<EnvInstance as OnInstance>::on_instance(|instance| {
instance.ecdsa_recover(signature, message_hash, output)
})
}
/// Returns an Ethereum address from the ECDSA compressed public key.
///
/// # Example
///
/// ```
/// let pub_key = [
/// 3, 110, 192, 35, 209, 24, 189, 55, 218, 250, 100, 89, 40, 76, 222, 208, 202, 127,
/// 31, 13, 58, 51, 242, 179, 13, 63, 19, 22, 252, 164, 226, 248, 98,
/// ];
/// let EXPECTED_ETH_ADDRESS = [
/// 253, 240, 181, 194, 143, 66, 163, 109, 18, 211, 78, 49, 177, 94, 159, 79, 207,
/// 37, 21, 191,
/// ];
/// let mut output = [0; 20];
/// ink_env::ecdsa_to_eth_address(&pub_key, &mut output);
/// assert_eq!(output, EXPECTED_ETH_ADDRESS);
/// ```
///
/// # Errors
///
/// - If the ECDSA public key cannot be recovered from the provided public key.
#[cfg(feature = "unstable-hostfn")]
pub fn ecdsa_to_eth_address(pubkey: &[u8; 33], output: &mut [u8; 20]) -> Result<()> {
<EnvInstance as OnInstance>::on_instance(|instance| {
instance.ecdsa_to_eth_address(pubkey, output)
})
}
/// Verifies a sr25519 signature.
///
/// # Example
///
/// ```
/// let signature: [u8; 64] = [
/// 184, 49, 74, 238, 78, 165, 102, 252, 22, 92, 156, 176, 124, 118, 168, 116, 247,
/// 99, 0, 94, 2, 45, 9, 170, 73, 222, 182, 74, 60, 32, 75, 64, 98, 174, 69, 55, 83,
/// 85, 180, 98, 208, 75, 231, 57, 205, 62, 4, 105, 26, 136, 172, 17, 123, 99, 90,
/// 255, 228, 54, 115, 63, 30, 207, 205, 131,
/// ];
/// let message: &[u8; 11] = b"hello world";
/// let pub_key: [u8; 32] = [
/// 212, 53, 147, 199, 21, 253, 211, 28, 97, 20, 26, 189, 4, 169, 159, 214, 130, 44,
/// 133, 88, 133, 76, 205, 227, 154, 86, 132, 231, 165, 109, 162, 125,
/// ];
///
/// let result = ink::env::sr25519_verify(&signature, message.as_slice(), &pub_key);
/// assert!(result.is_ok())
/// ```
///
/// # Errors
///
/// - If sr25519 signature cannot be verified.
///
/// **WARNING**: this function is from the [unstable interface](https://github.com/paritytech/polkadot-sdk/tree/master/substrate/frame/revive#unstable-interfaces)
/// which is unsafe and normally is not available on production chains.
#[cfg(feature = "unstable-hostfn")]
pub fn sr25519_verify(
signature: &[u8; 64],
message: &[u8],
pub_key: &[u8; 32],
) -> Result<()> {
<EnvInstance as OnInstance>::on_instance(|instance| {
instance.sr25519_verify(signature, message, pub_key)
})
}
/// Checks whether `addr` is a contract.
///
/// # Notes
///
/// If `addr` references a precompile address, the return value will be `true`.
///
/// The function [`caller_is_origin`] performs better when checking whether your
/// contract is being called by a contract or an account. It performs better
/// for this case as it does not require any storage lookups.
///
/// # Errors
///
/// If the returned value cannot be properly decoded.
pub fn is_contract(account: &Address) -> bool {
<EnvInstance as OnInstance>::on_instance(|instance| {
TypedEnvBackend::is_contract(instance, account)
})
}
/// Retrieves the code hash of the contract at the specified account id.
///
/// # Errors
///
/// - If no code hash was found for the specified account id.
/// - If the returned value cannot be properly decoded.
pub fn code_hash(addr: &Address) -> core::result::Result<H256, CodeHashErr> {
<EnvInstance as OnInstance>::on_instance(|instance| {
TypedEnvBackend::code_hash(instance, addr)
})
}
/// Retrieves the code hash of the currently executing contract.
///
/// # Errors
///
/// If the returned value cannot be properly decoded.
pub fn own_code_hash() -> H256 {
<EnvInstance as OnInstance>::on_instance(|instance| {
TypedEnvBackend::own_code_hash(instance)
})
}
/// Checks whether the caller of the current contract is the origin of the whole call
/// stack.
///
/// Prefer this over [`is_contract`] when checking whether your contract is being called
/// by a contract or a plain account. The reason is that it performs better since it does
/// not need to do any storage lookups.
///
/// A return value of `true` indicates that this contract is being called by a plain
/// account. and `false` indicates that the caller is another contract.
///
/// # Errors
///
/// If the returned value cannot be properly decoded.
pub fn caller_is_origin() -> bool {
<EnvInstance as OnInstance>::on_instance(|instance| {
TypedEnvBackend::caller_is_origin(instance)
})
}
/// Checks whether the caller of the current contract is root.
///
/// Note that only the origin of the call stack can be root. Hence this function returning
/// `true` implies that the contract is being called by the origin.
///
/// A return value of `true` indicates that this contract is being called by a root
/// origin, and `false` indicates that the caller is a signed origin.
///
/// # Errors
///
/// If the returned value cannot be properly decoded.
pub fn caller_is_root() -> bool {
<EnvInstance as OnInstance>::on_instance(|instance| {
TypedEnvBackend::caller_is_root(instance)
})
}
/// Replace the contract code at the specified address with new code.
///
/// # Note
///
/// There are a few important considerations which must be taken into account when
/// using this API:
///
/// 1. The storage at the code hash will remain untouched.
///
/// Contract developers **must ensure** that the storage layout of the new code is
/// compatible with that of the old code.
///
/// 2. The contract address (`AccountId`) remains the same, while the `code_hash` changes.
///
/// Contract addresses are initially derived from `hash(deploying_address ++ code_hash ++
/// salt)`. This makes it possible to determine a contracts address (`AccountId`) using
/// the `code_hash` of the *initial* code used to instantiate the contract.
///
/// However, because `set_code_hash` can modify the underlying `code_hash` of a contract,
/// it should not be relied upon that a contracts address can always be derived from its
/// stored `code_hash`.
///
/// 3. Re-entrant calls use new `code_hash`.
///
/// If a contract calls into itself after changing its code the new call would use the new
/// code. However, if the original caller panics after returning from the sub call it
/// would revert the changes made by `set_code_hash` and the next caller would use the old
/// code.
///
/// # Errors
///
/// todo: this enum variant no longer exists
/// `ReturnCode::CodeNotFound` in case the supplied `code_hash` cannot be found on-chain.
///
/// # Storage Compatibility
///
/// When the smart contract code is modified,
/// it is important to observe an additional virtual restriction
/// that is imposed on this procedure:
/// you should not change the order in which the contract state variables
/// are declared, nor their type.
///
/// Violating the restriction will not prevent a successful compilation,
/// but will result in the mix-up of values or failure to read the storage correctly.
/// This can result in severe errors in the application utilizing the contract.
///
/// If the storage of your contract looks like this:
///
/// ```ignore
/// #[ink(storage)]
/// pub struct YourContract {
/// x: u32,
/// y: bool,
/// }
/// ```
///
/// The procedures listed below will make it invalid:
///
/// Changing the order of variables:
///
/// ```ignore
/// #[ink(storage)]
/// pub struct YourContract {
/// y: bool,
/// x: u32,
/// }
/// ```
///
/// Removing existing variable:
///
/// ```ignore
/// #[ink(storage)]
/// pub struct YourContract {
/// x: u32,
/// }
/// ```
///
/// Changing type of a variable:
///
/// ```ignore
/// #[ink(storage)]
/// pub struct YourContract {
/// x: u64,
/// y: bool,
/// }
/// ```
///
/// Introducing a new variable before any of the existing ones:
///
/// ```ignore
/// #[ink(storage)]
/// pub struct YourContract {
/// z: Vec<u32>,
/// x: u32,
/// y: bool,
/// }
/// ```
///
/// Please refer to the
/// [Open Zeppelin docs](https://docs.openzeppelin.com/upgrades-plugins/1.x/writing-upgradeable#modifying-your-contracts)