bitpro가 원문에서 글자만 모은 내용이에요. 표·그림·수식은 빠지거나 깨질 수 있어요. 전체 73쪽 중 17쪽
installment of the series will therefore guide you through the steps necessary to deploy and interact with the `HelloStarknet` contract on Starknet Sepolia.
## Deploying a new Sepolia account
Similar to interacting with a Starknet Devnet instance, to interact with Starknet Sepolia you first need an account. However, instead fetching a predeployed Sepolia account, we will create a *new* account and deploy it using `sncast` ourselves.
<Note>
To learn how to fetch a predeployed Sepolia account, see [Fetching a predeployed Sepolia account](/build/quickstart/appendix#fetching-a-predeployed-sepolia-account).
</Note>
To create the account's information (private key, address, etc.), navigate into the `hello_starknet` directory created in [Generating `HelloStarknet`](/build/quickstart/hellostarknet#generating-hellostarknet) and run:
```bash theme={null}
sncast account create \
--network=sepolia \
--name=sepolia
```
When run, the command shows instructions on how to prefund the account before proceeding, which can be done using the [Starknet Sepolia faucet](https://starknet-faucet.vercel.app/).
<Note>
Prefunding the account is required because deploying an account involves sending a `DEPLOY_ACCOUNT` transaction, which requires the account to contain enough STRK to pay for the transaction fee.
</Note>
Once your account is funded, you can deploy it by running:
```bash theme={null}
sncast account deploy \
--network sepolia \
--name sepolia \
--silent
```
If successful, the result should resemble the following:
```console theme={null}
Success: Account deployed
Transaction Hash: 0x01340c0328b037bab85d53dd1b3b8040b0e0f4be58a42a94f554c9bf6e5bf30d
To see invocation details, visit:
transaction: https://sepolia.starkscan.co/tx/0x01340c0328b037bab85d53dd1b3b8040b0e0f4be58a42a94f554c9bf6e5bf30d
```
## Deploying `HelloStarknet` on Sepolia
Unlike when using a Starknet Devnet instance, there's no need for us to declare `HelloStarknet` on Sepolia as it has already been declared before (remember: declaration is a one-time process for each unique contract code). To verify that, you can try declaring it by navigating into the `hello_starknet` directory created in [Generating `HelloStarknet`](/build/quickstart/hellostarknet#generating-hellostarknet), running:
```bash theme={null}
sncast --account=sepolia declare \
--contract-name=HelloStarknet \
--network=sepolia
```
The result should resemble to the following:
```console theme={null}
command: declare
error: Transaction execution error = TransactionExecutionErrorData {
transaction_index: 0,
execution_error: Message(
"Class with hash 0x051e0d3b26fb79035afdc64d2214eb18291629b4f2ef132e79c3f3fbe1ba57c4 is already declared."
)
}
```
With `HelloStarknet` already declared, you can deploy an instance of it by running:
```bash theme={null}
sncast --account=sepolia deploy \
--class-hash=0x051e0d3b26fb79035afdc64d2214eb18291629b4f2ef132e79c3f3fbe1ba57c4 \
--network=sepolia
```
If successful, the result should resemble the following:
```console theme={null}
Success: Deployment completed
Contract Address: 0x05fe561f0907f61b1099ba64ee18a5250606d43d00d4f296ba622d287ceb2538
Transaction Hash: 0x0723a63261d2df60f571df8a2b8c8c64694278aae66481a0584445c03234d83f
To see deployment details, visit:
contract: https://sepolia.starkscan.co/contract/0x05fe561f0907f61b1099ba64ee18a5250606d43d00d4f296ba622d287ceb2538
transaction: https://sepolia.starkscan.co/tx/0x0723a63261d2df60f571df8a2b8c8c64694278aae66481a0584445c03234d83f
```
<Warning>
Your deployed contract's address will be different than the one listed above. Make sure to use the address of your own deployed contract in the following section.
</Warning>
## Interacting with `HelloStarknet` on Sepolia
Once your instance of `HelloStarknet` is deployed, you can invoke its `increase_balance` function by running:
```bash theme={null}
sncast --account=sepolia invoke \
--contract-address=<YOUR_CONTRACT_ADDRESS> \
--function=increase_balance \
--arguments=66 \
--network=sepolia
```
If successful, the result should resemble the following:
```console theme={null}
Success: Invoke completed
Transaction Hash: 0x02b900ba6bfb6a7d256d34c5d3a895abbfa0805d23f80253958e101069700020
To see invocation details, visit:
transaction: https://sepolia.starkscan.co/tx/0x02b900ba6bfb6a7d256d34c5d3a895abbfa0805d23f80253958e101069700020
```
Once the invoke transaction is accepted on Starknet Sepolia, you can call your deployed contract's `get_balance` function to confirm that your deployed contract's storage — and by extension, the state of Starknet Sepolia — has indeed changed, by running:
```bash theme={null}
sncast call \
--contract-address=<YOUR_CONTRACT_ADDRESS> \
--function=get_balance \
--network=sepolia
```
If all goes well, the result should resemble the following ($66_{10} = 42_{16}$):
```console theme={null}
Success: Call completed
Response: 0x42
Response Raw: [0x42]
```
# Account abstraction
Source: https://docs.starknet.io/build/starknet-by-example/advanced/account-abstraction
An account is an unique entity that can send transactions, users usually use wallets to manage their accounts.
Historically, in Ethereum, all accounts were Externally Owned Accounts (*EOA*) and were controlled by private keys. This is a simple and secure way to manage accounts, but it has limitations as the account logic is hardcoded in the protocol.
Account Abstraction (*AA*) is the concept behind abstracting parts of the account logic to allow for a more flexible account system.
This replaces EOA with Account Contracts, which are smart contracts that implement the account logic. This opens up a lot of possibilities that can significantly improve the user experience when dealing with accounts.
On Starknet, Account Abstraction is natively supported, and all accounts are Account Contracts.
## Account Contract
A smart contract must follow the Standard Account Interface specification defined in the [SNIP-6](https://github.com/starknet-io/SNIPs/blob/main/SNIPS/snip-6.md).
In practice, this means that the contract must implement the `SRC6` and `SRC5` interfaces to be considered an account contract.
### SNIP-6: SRC6 + SRC5
```rust theme={null}
/// @title Represents a call to a target contract
/// @param to The target contract address
/// @param selector The target function selector
/// @param calldata The serialized function parameters
struct Call {
to: ContractAddress,
selector: felt252,
calldata: Array<felt252>
}
```
The `Call` struct is used to represent a call to a function (`selector`) in a target contract (`to`) with parameters (`calldata`). It is available under the `starknet::account` module.
```rust theme={null}
/// @title SRC-6 Standard Account
trait ISRC6 {
/// @notice Execute a transaction through the account
/// @param calls The list of calls to execute
/// @return The list of each call's serialized return value
fn __execute__(calls: Array<Call>) -> Array<Span<felt252>>;
/// @notice Assert whether the transaction is valid to be executed
/// @param calls The list of calls to execute
/// @return The string 'VALID' represented as felt when is valid
fn __validate__(calls: Array<Call>) -> felt252;
/// @notice Assert whether a given signature for a given hash is valid
/// @param hash The hash of the data
/// @param signature The signature to validate
/// @return The string 'VALID' represented as felt when the signature is valid
fn is_valid_signature(hash: felt252, signature: Array<felt252>) -> felt252;
}
```
A transaction can be represented as a list of calls `Array<Call>` to other contracts, with atleast one call.
* `__execute__`: Executes a transaction after the validation phase. Returns an array of the serialized return of value (`Span<felt252>`) of each call.
* `__validate__`: Validates a transaction by verifying some predefined rules, such as the signature of the transaction. Returns the `VALID` short string (as a felt252) if the transaction is valid.
* `is_valid_signature`: Verify that a given signature is valid. This is mainly used by applications for authentication purposes.
Both `__execute__` and `__validate__` functions are exclusively called by the Starknet protocol.
```rust theme={null}
/// @title SRC-5 Standard Interface Detection
trait ISRC5 {
/// @notice Query if a contract implements an interface
/// @param interface_id The interface identifier, as specified in SRC-5
/// @return `true` if the contract implements `interface_id`, `false` otherwise
fn supports_interface(interface_id: felt252) -> bool;
}
```
The interface identifiers of both `SRC5` and `SRC6` must be published with `supports_interface`.
### Minimal account contract Executing Transactions
In this example, we will implement a minimal account contract that can validate and execute transactions.
```rust theme={null}
use starknet::account::Call;
#[starknet::interface]
trait ISRC6<TContractState> {
fn execute_calls(self: @TContractState, calls: Array<Call>) -> Array<Span<felt252>>;
fn validate_calls(self: @TContractState, calls: Array<Call>) -> felt252;
fn is_valid_signature(
self: @TContractState, hash: felt252, signature: Array<felt252>,
) -> felt252;
}
#[starknet::contract]
mod simpleAccount {
use super::ISRC6;
use starknet::account::Call;
use core::num::traits::Zero;
use core::ecdsa::check_ecdsa_signature;
use starknet::storage::{StoragePointerWriteAccess, StoragePointerReadAccess};
// Implement SRC5 with openzeppelin
use openzeppelin_account::interface;
use openzeppelin_introspection::src5::SRC5Component;
component!(path: SRC5Component, storage: src5, event: SRC5Event);
#[abi(embed_v0)]
impl SRC5Impl = SRC5Component::SRC5Impl<ContractState>;
impl SRC5InternalImpl = SRC5Component::InternalImpl<ContractState>;
#[storage]
struct Storage {
#[substorage(v0)]
src5: SRC5Component::Storage,
public_key: felt252,
}
#[constructor]
fn constructor(ref self: ContractState, public_key: felt252) {
self.src5.register_interface(interface::ISRC6_ID);
self.public_key.write(public_key);
}
#[event]
#[derive(Drop, starknet::Event)]
enum Event {
#[flat]
SRC5Event: SRC5Component::Event,
}
#[abi(embed_v0)]
impl SRC6 of ISRC6<ContractState> {
fn execute_calls(self: @ContractState, calls: Array<Call>) -> Array<Span<felt252>> {
assert(starknet::get_caller_address().is_zero(), "Not Starknet Protocol");
let Call { to, selector, calldata } = calls.at(0);
let res = starknet::syscalls::call_contract_syscall(*to, *selector, *calldata).unwrap();
array![res]
}
fn validate_calls(self: @ContractState, calls: Array<Call>) -> felt252 {
assert(starknet::get_caller_address().is_zero(), "Not Starknet Protocol");
let tx_info = starknet::get_tx_info().unbox();
let tx_hash = tx_info.transaction_hash;
let signature = tx_info.signature;
if self._is_valid_signature(tx_hash, signature) {
starknet::VALIDATED
} else {
0
}
}
fn is_valid_signature(
self: @ContractState, hash: felt252, signature: Array<felt252>,
) -> felt252 {
if self._is_valid_signature(hash, signature.span()) {
starknet::VALIDATED
} else {
0
}
}
}
#[generate_trait]
impl SignatureVerificationImpl of SignatureVerification {
fn _is_valid_signature(
self: @ContractState, hash: felt252, signature: Span<felt252>,
) -> bool {
check_ecdsa_signature(
hash, self.public_key.read(), *signature.at(0_u32), *signature.at(1_u32),
)
}
}
}
```
# Commit-Reveal
Source: https://docs.starknet.io/build/starknet-by-example/advanced/commit-reveal
The Commit-Reveal pattern is a fundamental blockchain pattern that enables to:
1. Commit to a value without revealing it *(commit phase)*
2. Reveal the value later to prove they knew it in advance *(reveal phase)*
Some use cases:
* **Blind Auctions**: Bidders commit to their bids first, then reveal them after the bidding period
* **Voting Systems**: Voters commit their votes early, revealing them only after voting ends
* **Knowledge Proofs/Attestations**: Proving you knew information at a specific time without revealing it immediately
* **Fair Random Number Generation**: Players commit to random numbers that get combined later, making it harder to manipulate the outcome
## How It Works
1. **Commit Phase**:
* User generates a value (`secret`)
* User creates a hash of this value
* User submits only the hash on-chain (`commit`)
2. **Reveal Phase**:
* User submits the original value (`reveal`)
* Contract verifies that the hash of the submitted value matches the previously committed hash
* If it matches then it proves that the user knew the value at the commitment time
## Minimal commit-reveal contract:
```rust theme={null}
#[starknet::interface]
pub trait ICommitmentRevealTrait<T> {
fn commit(ref self: T, commitment: felt252);
fn reveal(self: @T, secret: felt252) -> bool;
}
#[starknet::contract]
mod CommitmentRevealTraits {
use starknet::storage::{StoragePointerWriteAccess, StoragePointerReadAccess};
use core::hash::HashStateTrait;
use core::pedersen::PedersenTrait;
#[storage]
struct Storage {
commitment: felt252,
}
#[abi(embed_v0)]
impl CommitmentRevealTrait of super::ICommitmentRevealTrait<ContractState> {
fn commit(ref self: ContractState, commitment: felt252) {
self.commitment.write(commitment);
}
fn reveal(self: @ContractState, secret: felt252) -> bool {
let hash = PedersenTrait::new(secret).finalize();
self.commitment.read() == hash
}
}
}
```
Usage example:
```rust theme={null}
// Off-chain, compute the commitment hash for secret
let secret = "My secret";
let offchain_commitment = PedersenTrait::new(secret).finalize();
// Commit on-chain
contract.commit(offchain_commitment);
// Reveal on-chain and assert the result
let reveal_result = contract.reveal(secret);
```
Some considerations:
* The commit phase must complete before any reveals can start
* Users might choose not to reveal if the outcome is unfavorable (consider adding stake/slashing mechanics to ensure reveals)
# Solidity compatible hashing
Source: https://docs.starknet.io/build/starknet-by-example/advanced/hash-solidity-compatible
This contract demonstrates Keccak hashing in Cairo to match Solidity's keccak256. While both use Keccak, their endianness differs: Cairo is little-endian, Solidity big-endian. The contract achieves compatibility by hashing in big-endian using `keccak_u256s_be_inputs`, and reversing the bytes of the result with `u128_byte_reverse`.
For example:
```rust theme={null}
#[starknet::interface]
pub trait ISolidityHashExample<TContractState> {
fn hash_data(ref self: TContractState, input_data: Span<u256>) -> u256;
}
#[starknet::contract]
mod SolidityHashExample {
use core::keccak::keccak_u256s_be_inputs;
use core::integer;
#[storage]
struct Storage {}
#[abi(embed_v0)]
impl SolidityHashExample of super::ISolidityHashExample<ContractState> {
fn hash_data(ref self: ContractState, input_data: Span<u256>) -> u256 {
let hashed = keccak_u256s_be_inputs(input_data);
// Split the hashed value into two 128-bit segments
let low: u128 = hashed.low;
let high: u128 = hashed.high;
// Reverse each 128-bit segment
let reversed_low = integer::u128_byte_reverse(low);
let reversed_high = integer::u128_byte_reverse(high);
// Reverse merge the reversed segments back into a u256 value
let compatible_hash = u256 { low: reversed_high, high: reversed_low };
compatible_hash
}
}
}
```
# Hashing
Source: https://docs.starknet.io/build/starknet-by-example/advanced/hashing
Hashing is a cryptographic technique that allows you to transform a variable length input into a fixed length output.
The resulting output is called a hash and it's completely different from the input.
Hash functions are deterministic, meaning that the same input will always produce the same output.
The two hash functions provided by the Cairo library are `Poseidon` and `Pedersen`.
Pedersen hashes were used in the past (but are still used in some scenarios for backward compatibility), while Poseidon hashes are the standard nowadays since they were designed to be very efficient for Zero Knowledge proof systems.
In Cairo, it's possible to hash all types that can be converted to `felt252` since they natively implement the `Hash` trait. It's also possible to hash more complex types, like structs, by deriving the Hash trait with the `#[derive(Hash)]` attribute, but only if all the struct's fields are themselves hashable.
To hash a value, you first need to initialize a hash state with the `new` method of the `HashStateTrait`. Then, you can update the hash state with the `update` method. You can accumulate multiple updates if necessary. Finally, the `finalize` method returns the final hash value as a `felt252`.
```rust theme={null}
#[starknet::interface]
pub trait IHashTrait<T> {
fn save_user_with_poseidon(
ref self: T, id: felt252, username: felt252, password: felt252,
) -> felt252;
fn save_user_with_pedersen(
ref self: T, id: felt252, username: felt252, password: felt252,
) -> felt252;
}
#[starknet::contract]
mod HashTraits {
use starknet::storage::StoragePointerWriteAccess;
use core::hash::{HashStateTrait, HashStateExTrait};
use core::{pedersen::PedersenTrait, poseidon::PoseidonTrait};
#[storage]
struct Storage {
user_hash_poseidon: felt252,
user_hash_pedersen: felt252,
}
#[derive(Drop, Hash)]
struct LoginDetails {
username: felt252,
password: felt252,
}
#[derive(Drop, Hash)]
struct UserDetails {
id: felt252,
login: LoginDetails,
}
#[abi(embed_v0)]
impl HashTrait of super::IHashTrait<ContractState> {
fn save_user_with_poseidon(
ref self: ContractState, id: felt252, username: felt252, password: felt252,
) -> felt252 {
let login = LoginDetails { username, password };
let user = UserDetails { id, login };
let poseidon_hash = PoseidonTrait::new().update_with(user).finalize();
self.user_hash_poseidon.write(poseidon_hash);
poseidon_hash
}
fn save_user_with_pedersen(
ref self: ContractState, id: felt252, username: felt252, password: felt252,
) -> felt252 {
let login = LoginDetails { username, password };
let user = UserDetails { id, login };
let pedersen_hash = PedersenTrait::new(0).update_with(user).finalize();
self.user_hash_pedersen.write(pedersen_hash);
pedersen_hash
}
}
}
```
# Library calls
Source: https://docs.starknet.io/build/starknet-by-example/advanced/library-calls
External calls can be made on Starknet by two means: Contract dispatchers or Library dispatchers. Dispatchers are automatically created and exported by the compiler when a contract interface is defined.
With Contract dispatcher we are calling an already deployed contract (with associated state), therefore contract address is passed to the dispatcher to make the call. However, with library dispatcher we are simply making function calls to declared contract **classes** (stateless).
Contract dispatcher call is synonymous to external calls in Solidity, while library dispatcher call is synonymous to delegate call.
For further reading: [Cairo book](https://book.cairo-lang.org/ch15-03-executing-code-from-another-class.html#library-calls)
```rust theme={null}
#[starknet::interface]
pub trait IMathUtils<T> {
fn add(ref self: T, x: u32, y: u32) -> u32;
fn set_class_hash(ref self: T, class_hash: starknet::ClassHash);
}
// contract A
#[starknet::contract]
pub mod MathUtils {
#[storage]
struct Storage {}
#[abi(embed_v0)]
impl ImathUtilsImpl of super::IMathUtils<ContractState> {
fn add(ref self: ContractState, x: u32, y: u32) -> u32 {
x + y
}
fn set_class_hash(ref self: ContractState, class_hash: starknet::ClassHash) {}
}
}
// contract B to make library call to the class of contract A
#[starknet::contract]
pub mod MathUtilsLibraryCall {
use super::{IMathUtilsDispatcherTrait, IMathUtilsLibraryDispatcher};
use starknet::storage::{StoragePointerReadAccess, StoragePointerWriteAccess};
#[storage]
struct Storage {
value: u32,
lib_class_hash: starknet::ClassHash,
}
#[abi(embed_v0)]
impl MathUtils프로젝트로 돌아가기