bitpro가 원문에서 글자만 모은 내용이에요. 표·그림·수식은 빠지거나 깨질 수 있어요. 전체 38쪽 중 10쪽
olidity src/Oracle.sol theme={null}
constructor(address oracleAddress) {
connect = IConnectOracle(oracleAddress);
}
```
Once the constructor is implemented, move on to defining the different functions
that the contract will have.
* `oracle_get_price`: This function will return the price of a single asset pair
* `oracle_get_prices`: This function will return the price of multiple asset
pairs
```solidity src/Oracle.sol theme={null}
function oracle_get_price() external view returns (uint256 price, uint256 timestamp) {
IConnectOracle.Price memory p = connect.get_price("BTC/USD");
return (p.price, p.timestamp);
}
function oracle_get_prices() external view returns (uint256[] memory prices) {
string[] memory pair_ids = new string[](2);
pair_ids[0] = "BTC/USD";
pair_ids[1] = "ETH/USD";
IConnectOracle.Price[] memory result = connect.get_prices(pair_ids);
prices = new uint256[](result.length);
for (uint256 i = 0; i < result.length; i++) {
prices[i] = result[i].price;
}
}
```
The complete contract will then look like this:
```solidity src/Oracle.sol theme={null}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
interface IConnectOracle {
struct Price {
uint256 price;
uint256 timestamp;
uint64 height;
uint64 nonce;
uint64 decimal;
uint64 id;
}
function get_price(string memory pair_id) external view returns (Price memory);
function get_prices(string[] memory pair_ids) external view returns (Price[] memory);
}
contract Oracle {
IConnectOracle public connect;
constructor(address oracleAddress) {
connect = IConnectOracle(oracleAddress);
}
function oracle_get_price() external view returns (uint256 price, uint256 timestamp) {
IConnectOracle.Price memory p = connect.get_price("BTC/USD");
return (p.price, p.timestamp);
}
function oracle_get_prices() external view returns (uint256[] memory prices) {
string[] memory pair_ids = new string[](2);
pair_ids[0] = "BTC/USD";
pair_ids[1] = "ETH/USD";
IConnectOracle.Price[] memory result = connect.get_prices(pair_ids);
prices = new uint256[](result.length);
for (uint256 i = 0; i < result.length; i++) {
prices[i] = result[i].price;
}
return prices;
}
}
```
Running `forge compile` will fail unless you provide a test file that matches
the `Oracle.sol` contract. Foundry expects a test file like `Oracle.t.sol` to
exist and import the contract under test. To resolve this, rename the existing
test file `Counter.t.sol` to `Oracle.t.sol`.
```sh theme={null}
mv test/Counter.t.sol test/Oracle.t.sol
```
Also replace the file contents with placeholder content.
```solidity test/Oracle.t.sol theme={null}
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.24;
import {Test, console} from "forge-std/Test.sol";
contract OracleTest is Test {
}
```
Now running `forge compile` should work without any errors.
```sh theme={null}
forge compile
# [Expected Output]:
# [⠢] Compiling...
# [⠰] Compiling 27 files with 0.8.21
# [⠃] Solc 0.8.21 finished in 6.25s
# Compiler run successful!
```
## Deploying the Contract
Now that the contract is compiled and ready, you can deploy it to the MiniEVM.
To accomplish this, use Foundry's `forge script` command. First, create a script
file to handle the deployment. Create a new file named `Oracle.s.sol` in the
`script` directory.
```solidity script/Oracle.s.sol theme={null}
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.24;
import {Script, console} from "forge-std/Script.sol";
import {Oracle} from "../src/Oracle.sol";
contract OracleScript is Script {
Oracle public oracle;
function setUp() public {}
function run() public {
address oracleAddress = 0x031ECb63480983FD216D17BB6e1d393f3816b72F;
vm.startBroadcast();
oracle = new Oracle(oracleAddress);
vm.stopBroadcast();
}
}
```
Set your environment variables and run the deployment. Be sure to replace
`PRIVATE_KEY` with the deployer's private key, and `JSON_RPC_URL` with your
rollup's JSON-RPC endpoint.
```sh theme={null}
export PRIVATE_KEY=0x...
export JSON_RPC_URL=https://jsonrpc-evm-1.anvil.asia-southeast.initia.xyz
forge script script/Oracle.s.sol:OracleScript \
--rpc-url $JSON_RPC_URL \
--private-key $PRIVATE_KEY \
--broadcast \
--via-ir \
--with-gas-price 0 \
--skip-simulation
```
Output should look like this:
```sh theme={null}
[⠊] Compiling...
[⠊] Compiling 18 files with Solc 0.8.28
[⠒] Solc 0.8.28 finished in 918.49ms
Compiler run successful!
Script ran successfully.
SKIPPING ON-CHAIN SIMULATION.
##### 4303131403034904
✅ [Success] Hash: 0x8d9c488d7599fd867e45eee3b3a6ede24fec8f6459433051c341ef1937026bcf
Contract Address: 0x505500221090Cd06400125B4f41A266B89Ffd62e
Block: 10493369
Gas Used: 290728
✅ Sequence #1 on 4303131403034904 | Total Paid: 0. ETH (290728 gas * avg 0 gwei)
```
To query the `oracle_get_price()` function, use Foundry’s cast call command.
```sh theme={null}
cast call 0x505500221090Cd06400125B4f41A266B89Ffd62e "oracle_get_price()" --rpc-url $JSON_RPC_URL
```
Output should look like this:
```sh theme={null}
0x00000000000000000000000000000000000000000000000000000002c3cd0d430000000000000000000000000000000000000000000000001856610b4b695788
```
The output is an ABI-encoded hexadecimal result containing the price and
timestamp. The first 32 bytes represent the price, and the next 32 bytes
represent the timestamp.
| Field | ABI-Encoded Value | Decoded Value |
| --------- | ------------------ | ------------------- |
| Price | 0x2c3cd0d43 | 11874929987 |
| Timestamp | 0x1856610b4b695788 | 1753695806045116296 |
# Token Denom Conversion
Source: https://docs.initia.xyz/developers/developer-guides/vm-specific-tutorials/evm/cosmos-coin-to-erc20
[Tutorial GitHub Repository](https://github.com/initia-labs/examples/tree/main/evm/cosmos-coin-to-erc20)
This tutorial demonstrates how to convert between a hex-based ERC20 token
address and a Cosmos coin denom.
## Prerequisites
* [NodeJS](https://nodejs.org)
## Project Setup
First, create a new directory for your project.
```sh theme={null}
mkdir cosmos-coin-to-erc20
cd cosmos-coin-to-erc20
```
Next, initialize the project and create an `index.js` file in a `src` directory.
```sh theme={null}
npm init
touch src/index.js
```
## Development
For this tutorial, assume that you have an ERC20 token address
`0x5E5f1a92eECA58053E8364630b66763aa6265Ab0` that you want to convert to a
Cosmos coin denom, and then convert it back to an ERC20 token address.
First, initialize the variable for the chain's REST endpoint and the ERC20 token
address.
```js src/index.js theme={null}
const restUrl = `https://rest-evm-1.anvil.asia-southeast.initia.xyz`
const erc20Address = '0x5E5f1a92eECA58053E8364630b66763aa6265Ab0'
```
### ERC20 to Cosmos Denom
To actually do the conversion, use the REST's
`/minievm/evm/v1/denoms/{contractAddress}` endpoint.
```js src/index.js theme={null}
// previous code
async function erc20ToCoinDenom(contractAddress) {
const response = await fetch(
`${restUrl}/minievm/evm/v1/denoms/${contractAddress}`,
)
const data = await response.json()
return data
}
```
If the address is a valid ERC20 token address, the response just returns the
token's Cosmos coin denom.
```sh theme={null}
evm/5E5f1a92eECA58053E8364630b66763aa6265Ab0
```
### Cosmos Denom to ERC20 Address
To convert a Cosmos coin denom back to an ERC20 token address, use the REST's
`/minievm/evm/v1/contracts/by_denom?denom={denom}` endpoint.
```js src/index.js theme={null}
// previous code
async function coinDenomToErc20(denom) {
const response = await fetch(
`${restUrl}/minievm/evm/v1/contracts/by_denom?denom=${denom}`,
)
const data = await response.json()
return data
}
```
If the denom is a valid Cosmos coin denom, the response just returns the token's
ERC20 token address.
```sh theme={null}
0x5E5f1a92eECA58053E8364630b66763aa6265Ab0
```
The full code for the script, including the section to actually call the
function is as follows:
```js src/index.js theme={null}
const restUrl = `https://rest-evm-1.anvil.asia-southeast.initia.xyz`
const erc20Address = '0x5E5f1a92eECA58053E8364630b66763aa6265Ab0'
async function erc20ToCoinDenom(contractAddress) {
const response = await fetch(
`${restUrl}/minievm/evm/v1/denoms/${contractAddress}`,
)
const data = await response.json()
return data
}
async function coinDenomToErc20(denom) {
const response = await fetch(
`${restUrl}/minievm/evm/v1/contracts/by_denom?denom=${denom}`,
)
const data = await response.json()
return data
}
;(async () => {
const coinDenomResponse = await erc20ToCoinDenom(erc20Address)
console.log(coinDenomResponse.denom)
const erc20Response = await coinDenomToErc20(coinDenomResponse.denom)
console.log(erc20Response.address)
})()
```
If you run this script, you should see the following output:
```sh theme={null}
evm/5E5f1a92eECA58053E8364630b66763aa6265Ab0
0x5E5f1a92eECA58053E8364630b66763aa6265Ab0
```
# Creating Custom ERC20s
Source: https://docs.initia.xyz/developers/developer-guides/vm-specific-tutorials/evm/creating-erc20s/creating-custom-erc20s
[Tutorial GitHub Repository](https://github.com/initia-labs/examples/tree/main/evm/initia-custom-erc20)
## Prerequisites
### Foundry
For this tutorial, you will be using the
[Foundry](https://github.com/foundry-rs/foundry) toolkit to develop, compile,
and deploy your contracts. If you do not have Foundry installed, follow the
[Foundry installation instructions](https://getfoundry.sh/).
## Setup
First, create a new directory for your project.
```sh theme={null}
mkdir initia-erc20
cd initia-erc20
```
Next, initialize a new Foundry project inside that directory.
```sh theme={null}
forge init
```
Once the project is initialized, you can proceed to installing the required
dependencies needed for this tutorial. In this case, you only need Initia's
[EVM contracts](https://github.com/initia-labs/initia-evm-contracts).
```sh theme={null}
forge install initia-labs/initia-evm-contracts
```
## Implementing the Contract
Before writing the contract, first rename the template contract to
`NewInitiaERC20.sol`.
```sh theme={null}
mv src/Counter.sol src/NewInitiaERC20.sol
```
Then update the contract from the template to be your custom ERC20 contract.
Start by importing the `InitiaCustomERC20` contract from the
`@initia/initia-evm-contracts` package.
```solidity src/NewInitiaERC20.sol theme={null}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
import "initia-evm-contracts/src/InitiaCustomERC20.sol";
```
Next, extend the `InitiaCustomERC20` contract and add the constructor to
initialize the contract with the name, symbol, and decimals of your custom
ERC20. For this tutorial, you will simply customize the base contract by adding
a logic to mint tokens to the contract deployer during deployment.
```solidity src/NewInitiaERC20.sol theme={null}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
import "initia-evm-contracts/src/InitiaCustomERC20.sol";
/**
* @title NewInitiaERC20
* @dev Demo extension of InitiaERC20 token contract with initial minting functionality
*/
contract NewInitiaERC20 is InitiaERC20 {
/**
* @dev Constructor for creating a new InitiaERC20 token with initial minted supply
* @param name_ The name of the token
* @param symbol_ The symbol of the token
* @param decimals_ The number of decimal places for token precision
* @param mintedTokens_ The initial amount of tokens to mint to the contract deployer
*/
constructor(string memory name_, string memory symbol_, uint8 decimals_, uint256 mintedTokens_) InitiaERC20(name_, symbol_, decimals_) {
_mint(msg.sender, mintedTokens_);
}
}
```
The contract implementation is now ready. However, if you try to compile the
contract using `forge compile`, you will get an error.
This is because the default `Counter.t.sol` and `Counter.s.sol` expect the
original `Counter.sol` contract to be available. To fix this, rename
`Counter.t.sol` to `NewInitiaERC20.t.sol` and `Counter.s.sol` to
`NewInitiaERC20.s.sol`.
```sh theme={null}
mv test/Counter.t.sol test/NewInitiaERC20.t.sol
mv script/Counter.s.sol script/NewInitiaERC20.s.sol
```
Now replace the contents of the `NewInitiaERC20.t.sol` file with the following
placeholder content.
```solidity test/NewInitiaERC20.t.sol theme={null}
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.13;
import {Test, console} from "forge-std/Test.sol";
import {NewInitiaERC20} from "../src/NewInitiaERC20.sol";
contract NewInitiaERC20Test is Test {
}
```
And replace the contents of the `NewInitiaERC20.s.sol` file with following
placeholder content.
```solidity script/NewInitiaERC20.s.sol theme={null}
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.13;
import {Script} from "forge-std/Script.sol";
import {NewInitiaERC20} from "../src/NewInitiaERC20.sol";
contract NewInitiaERC20Script is Script {
NewInitiaERC20 public erc20;
function setUp() public {}
function run() public {
vm.startBroadcast();
erc20 = new NewInitiaERC20("New Initia ERC20", "NIERC20", 18, 1000000 * 10 ** 18);
vm.stopBroadcast();
}
}
```
Now running `forge compile` should work without any errors.
```sh theme={null}
forge compile
```
### Expected Output:
```sh theme={null}
[⠢] Compiling...
[⠰] Compiling 27 files with 0.8.21
[⠃] Solc 0.8.21 finished in 6.25s
Compiler run successful!
```
## Deploying the Contract
Now that the contract is compiled and ready, you can deploy it to the MiniEVM.
To accomplish this, use Foundry's `forge create` command
<Warning>
**Security Note:** In this tutorial, a private key is exported directly in the
terminal for simplicity. This is fine for *testnet* or *throwaway* accounts.
Do **not** use this method for accounts holding real funds. For production
usage, place sensitive keys in a `.env` file (ignored by git) or use a secure
key manager.
</Warning>
```sh theme={null}
export PRIVATE_KEY=0x...
export RPC_URL='https://jsonrpc-evm-1.anvil.asia-southeast.initia.xyz'
forge create src/NewInitiaERC20.sol:NewInitiaERC20 \
--rpc-url $RPC_URL \
--private-key $PRIVATE_KEY \
--legacy \
--broadcast \
--constructor-args "MyToken" "MTK" 18 100
```
### Expected Output:
```sh theme={null}
[⠊] Compiling...
No files changed, compilation skipped
Deployer: 0xc5D26D0281e28599c7790aacc810226BBDf0E431
Deployed to: 0x3cc54047D191eeeBDcde081D8708490F6df49Be8
Transaction hash: 0xed1d23b69014ee066be9b761df3c1fb28bedc46cc1c3f2188960550dbf7862a1
```
To confirm that the contract was deployed successfully, you can try querying the
balance of your deployer account using Foundry's `cast call` command.
```sh theme={null}
cast call 0x3cc54047D191eeeBDcde081D8708490F6df49Be8 \
"balanceOf(address)(uint256)" 0xc5D26D0281e28599c7790aacc810226BBDf0E431 \
--rpc-url "https://jsonrpc-evm-1.anvil.asia-southeast.initia.xyz"
```
### \[Expected Output]:
```sh theme={null}
100
```
# Creating Standard ERC20s via ERC20Factory
Source: https://docs.initia.xyz/developers/developer-guides/vm-specific-tutorials/evm/creating-erc20s/creating-standard-erc20s
[Tutorial GitHub Repository](https://github.com/initia-labs/examples/tree/main/evm/erc20-factory)
For developers looking to create standard ERC20 tokens on EVM rollups, the
recommended approach is to use the
[ERC20Factory](/resources/developer/contract-references/evm/erc20-factory)
contract.
## Project Setup
First, create a new project directory:
```sh theme={null}
mkdir erc20-factory
cd erc20-factory
```
Initialize the project and install the required dependencies:
```sh theme={null}
npm init
npm install viem
npm install dotenv
```
Create two directories:
* `src`: For your script files.
* `abis`: For your contract
[ABIs](https://www.alchemy.com/docs/smart-contract-abi).
```sh theme={null}
mkdir src
mkdir abis
```
Download the ERC20 and ERC20Factory ABIs into the `abis` directory:
```sh theme={null}
curl -o abis/erc20Abi.json \
https://raw.githubusercontent.com/initia-labs/examples/main/evm/erc20-factory/abis/erc20Abi.json
curl -o abis/erc20FactoryAbi.json \
https://raw.githubusercontent.com/initia-labs/examples/main/evm/erc20-factory/abis/erc20FactoryAbi.json
```
## Setting Up Environment Variables
Create a `.env` file in your project root:
```sh theme={null}
touch .env
```
This file will store your private environment variables, such as your wallet's
private key and the deployed ERC20Factory contract address. These values are
required for signing transactions and interacting with the MiniEVM.
The `ERC20Factory` contract is automatically deployed on all MiniEVM rollups as
part of the chain’s bootstrapping process.
To retrieve the deployed factory address, query
`{ROLLUP_REST_URL}/minievm/evm/v1/contracts/erc20_factory`.
`{ROLLUP_REST_URL}` refers to the REST endpoint of the rollup you are
interacting with.
Example:
```bash theme={null}
curl -X GET "https://rest-evm-1.anvil.asia-southeast.initia.xyz/minievm/evm/v1/contracts/erc20_factory" -H "accept: application/json"
```
Example response:
```json theme={null}
{
"address": "0xf36924c9C2aD25d73c43F6aC59BB6D06BC944D93"
}
```
Store this address in your `.env` file as `ERC20_FACTORY_ADDRESS`.
Next, export an EVM-compatible private key from your Ethereum wallet. This
private key will be used to sign and send transactions to the MiniEVM.
Your `.env` file should look like this:
```
PRIVATE_KEY={{ETHEREUM_PRIVATE_KEY}}
ERC20_FACTORY_ADDRESS={{FACTORY_CONTRACT_ADDRESS}}
```
<Warning>
Never share your `.env` file or private key. Anyone with this key can control
your account. Keep it local and **add `.env` to your `.gitignore`** so it is
never committed to Git.
</Warning>
## Development
### Creating the Chain Configuration File
To interact with the MiniEVM using Viem, you need a chain configuration file.
This file contains essential details about the chain, including the chain ID,
name, native currency, and RPC URLs.
Create a `chain.js` file in the `src` directory:
```sh theme={null}
touch src/chain.js
```
Add the following configuration:
```js theme={null}
const { defineChain } = require('viem')
const miniEVM = defineChain({
id: 2594729740794688,
name: 'MiniEVM',
nativeCurrency: {
decimals: 18,
name: 'Gas Token',
symbol: 'GAS',
},
rpcUrls: {
default: {
http: ['https://jsonrpc-evm-1.anvil.asia-southeast.initia.xyz'],
},
},
})
module.exports = miniEVM
```
### Interacting with the ERC20Factory Contract
Next, create a script to interact with the ERC20Factory contract:
```sh theme={null}
touch src/index.js
```
Start with the imports:
```js theme={null}
const {
createPublicClient,
createWalletClient,
decodeEventLog,
getContract,
http,
} = require('viem')
const { privateKeyToAccount } = require('viem/accounts')
const erc20Abi = require('../abis/erc20Abi.json')
const erc20FactoryAbi = require('../abis/erc20FactoryAbi.json')
const miniEVM = require('./chain')
```
Load the environment variables:
<Note>
You can also find factory addresses on the
[Networks](/resources/developer/initia-l1) page or by calling the
`/minievm/evm/v1/contracts/erc20_factory` endpoint on any MiniEVM rollup.
</Note>
```js theme={null}
require('dotenv').config()
const rawPrivateKey = process.env.PRIVATE_KEY
if (!rawPrivateKey) {
throw new Error('PRIVATE_KEY environment variable is not set.')
}
const privateKey = rawPrivateKey.startsWith('0x')
? rawPrivateKey
: `0x${rawPrivateKey}`
const erc20FactoryAddress = process.env.ERC20_FACTORY_ADDRESS
if (!erc20FactoryAddress) {
throw new Error('ERC20_FACTORY_ADDRESS environment variable is not set.')
}
```
To interact with the chain and contracts, create a wallet client and a public
client:
```js theme={null}
// Create an account from the private key.
const account = privateKeyToAccount(privateKey)
// Create a wallet client.
const client = createWalletClient({
account,
chain: miniEVM,
transport: http(),
})
// Create a public client.
const publicClient = createPublicClient({
chain: miniEVM,
transport: http(),
})
```
Now you can create a new ERC20 token u프로젝트로 돌아가기