bitpro가 원문에서 글자만 모은 내용이에요. 표·그림·수식은 빠지거나 깨질 수 있어요. 전체 38쪽 중 9쪽
gate governance coin to validators (staking)
```typescript theme={null}
const msg = new MsgDelegate(
'init1kdwzpz3wzvpdj90gtga4fw5zm9tk4cyrgnjauu', // delegator address
'initvaloper14qekdkj2nmmwea4ufg9n002a3pud23y8l3ep5z', // validator's operator address
'100000uinit', // delegate amount
)
```
## VM-Specific Messages
#### MoveVM
* `MsgExecute()`: execute move contract entry functions
```typescript theme={null}
const msg = new MsgExecute(
'init1kdwzpz3wzvpdj90gtga4fw5zm9tk4cyrgnjauu', // sender address
'0x1', // module owner address
'dex', // module name
'swap_script', // function name
[], // type arguments
[
bcs.address().serialize('0x2').toBase64(), // arguments, BCS-encoded
bcs.address().serialize('0x3').toBase64(), // arguments, BCS-encoded
bcs.u64().serialize(10000).toBase64(), // arguments, BCS-encoded
],
)
```
#### WasmVM
* `MsgStoreCode()`: store wasm contract code
```typescript theme={null}
const wasmByteCode = fs
.readFileSync('./wasm-modules/miniwasm/example.wasm') // path of wasm file
.toString('base64')
const msg = new MsgStoreCode(
'init1kdwzpz3wzvpdj90gtga4fw5zm9tk4cyrgnjauu', // sender address
wasmByteCode, // raw or gzip compressed wasm bytecode
undefined, // instantiate permission (optional)
)
```
* `MsgInstantiateContract()`: instantiate wasm contract
```typescript theme={null}
const instantiateMsg = Buffer.from(
JSON.stringify({
init_list: ['init1kdwzpz3wzvpdj90gtga4fw5zm9tk4cyrgnjauu'],
}),
).toString('base64')
const msg = new MsgInstantiateContract(
'init1kdwzpz3wzvpdj90gtga4fw5zm9tk4cyrgnjauu', // sender address
'init1kdwzpz3wzvpdj90gtga4fw5zm9tk4cyrgnjauu', // admin address
9, // code id
'example', // label
instantiateMsg, // instantiate msg
new Coins(), // init funds
)
```
* `MsgExecuteContract()`: execute wasm contract functions
```typescript theme={null}
const jsonEncodedMsg = Buffer.from(
JSON.stringify({
prepare_point: {
stage: 1,
},
}),
).toString('base64')
const msg = new MsgExecuteContract(
'init1kdwzpz3wzvpdj90gtga4fw5zm9tk4cyrgnjauu', // sender address
'init1jue5rlc9dkurt3etr57duutqu7prchqrk2mes2227m52kkrual3qdrydg6', // contract address
jsonEncodedMsg, // json encoded input msg
new Coins(), // coins transferred to the contract on execution
)
```
#### EVM
* `MsgCreate()`: create EVM contract code
```typescript theme={null}
const contractInfo = JSON.parse(
fs
.readFileSync(
'../solidity/evm-example/artifacts/contracts/example.sol/example.json', // path of build response
)
.toString(),
)
const msg = new MsgCreate(
'init1kdwzpz3wzvpdj90gtga4fw5zm9tk4cyrgnjauu', // sender address
contractInfo.bytecode.slice(2), // hex encoded raw contract bytes code
)
```
* `MsgCall()`: execute EVM contract functions
```typescript theme={null}
const contractAddress = '0x1kdwzpz3wzvpdj90gtga4fw5zm9tk4cyrgnjauu'
const contractInfo = JSON.parse(
fs
.readFileSync(
'../solidity/evm-example/artifacts/contracts/example.sol/example.json', // path of build response
)
.toString(),
)
const contract = new ethers.Contract(contractAddress, contractInfo.abi)
const msg = new MsgCall(
'init1kdwzpz3wzvpdj90gtga4fw5zm9tk4cyrgnjauu', // sender address
contractAddress, // contract address
contract.interface.encodeFunctionData('preparePoint', [2]).slice(2), // hex encoded execution input bytes
)
```
# Sending Transactions
Source: https://docs.initia.xyz/developers/developer-guides/tools/sdks/initia-js/transactions/sending-transactions
Sending transactions using InitiaJS is straightforward. First, import the
necessary classes and functions.
```ts theme={null}
import {
Wallet,
RESTClient,
MnemonicKey,
MsgSend,
Tx,
WaitTxBroadcastResult,
} from '@initia/initia.js'
```
Next, set up your environment variables. You will need the following:
* `MNEMONIC`: The mnemonic of the account that will be sending the transaction.
* `REST_URL`: The URL of the Initia REST.
* `GAS_PRICES`: The gas prices for the transaction.
* `SENDER_ADDRESS`: The address of the account that will be sending the
transaction.
* `RECIPIENT_ADDRESS`: The address of the account that will be receiving the
transaction.
* `AMOUNT`: The amount of tokens to send.
```ts theme={null}
if (!process.env.MNEMONIC) {
throw new Error('MNEMONIC environment variable is required')
}
const mnemonic = process.env.MNEMONIC
const restUrl = process.env.REST_URL || 'https://rest.testnet.initia.xyz'
const gasPrices = process.env.GAS_PRICES || '0.015uinit' // Will be INIT for mainnet
const senderAddress =
process.env.SENDER_ADDRESS || 'init1w4cqq6udjqtvl5xx0x6gjeyzgwtze8c05kysnu'
const recipientAddress =
process.env.RECIPIENT_ADDRESS || 'init1w4cqq6udjqtvl5xx0x6gjeyzgwtze8c05kysnu'
const amount = process.env.AMOUNT || '1000uinit'
```
You can then use these variables to ultimately create the `wallet` client, as
well as the `sendMsg` object. Since for this example you're making a token
transfer, we'll use the `MsgSend` object. But the SDK provides many other
message types for different actions related to staking, governance, and more.
```ts theme={null}
const key: MnemonicKey = new MnemonicKey({ mnemonic }) // Create a key from the mnemonic
const restClient: RESTClient = new RESTClient(restUrl, { gasPrices })
const wallet: Wallet = new Wallet(restClient, key)
const sendMsg: MsgSend = new MsgSend(senderAddress, recipientAddress, amount)
```
Next, create the function to send the transaction.
* First, create the transaction by calling `wallet.createAndSignTx`. This
function takes in the raw message object, signs it using the `wallet`, and
returns a signed transaction object.
* Then, broadcast the transaction by calling `restClient.tx.broadcast`. This
function takes in the signed transaction object and broadcasts it to the
network.
```ts theme={null}
async function sendTransaction(): Promise<WaitTxBroadcastResult> {
try {
const signedTx: Tx = await wallet.createAndSignTx({
msgs: [sendMsg],
memo: 'memo',
})
const result: WaitTxBroadcastResult =
await restClient.tx.broadcast(signedTx)
console.log('Transaction successful')
console.log('Transaction hash:', result.txhash)
return result
} catch (error: unknown) {
if (error instanceof Error) {
console.error('Transaction failed:', error.message)
} else {
console.error('Transaction failed with an unknown error')
}
throw error
}
}
```
Finally, call the function to send the transaction.
```ts theme={null}
sendTransaction()
.then(() => process.exit(0))
.catch(() => process.exit(1))
```
If you then run the script using `npx ts-node src/sending-transactions.ts`, you
should see an output similar to the following:
```
Transaction successful
Transaction hash: 4F0B810D15FA7D6A2B9EC2B98B263B0A20E791A8DABCB549620445941B25C699
```
### Full Example
```ts src/sending-transactions.ts theme={null}
import {
Wallet,
RESTClient,
MnemonicKey,
MsgSend,
Tx,
WaitTxBroadcastResult,
} from '@initia/initia.js'
const mnemonic = process.env.MNEMONIC
const restUrl = process.env.REST_URL || 'https://rest.testnet.initia.xyz'
const gasPrices = process.env.GAS_PRICES || '0.015uinit' // Will be INIT for mainnet
const senderAddress =
process.env.SENDER_ADDRESS || 'init1w4cqq6udjqtvl5xx0x6gjeyzgwtze8c05kysnu'
const recipientAddress =
process.env.RECIPIENT_ADDRESS || 'init1w4cqq6udjqtvl5xx0x6gjeyzgwtze8c05kysnu'
const amount = process.env.AMOUNT || '1000uinit'
const key: MnemonicKey = new MnemonicKey({ mnemonic })
const restClient: RESTClient = new RESTClient(restUrl, { gasPrices })
const wallet: Wallet = new Wallet(restClient, key)
const sendMsg: MsgSend = new MsgSend(senderAddress, recipientAddress, amount)
async function sendTransaction(): Promise<WaitTxBroadcastResult> {
try {
const signedTx: Tx = await wallet.createAndSignTx({
msgs: [sendMsg],
memo: 'memo',
})
const result: WaitTxBroadcastResult =
await restClient.tx.broadcast(signedTx)
console.log('Transaction successful')
console.log('Transaction hash:', result.txhash)
return result
} catch (error: unknown) {
if (error instanceof Error) {
console.error('Transaction failed:', error.message)
} else {
console.error('Transaction failed with an unknown error')
}
throw error
}
}
sendTransaction()
.then(() => process.exit(0))
.catch(() => process.exit(1))
```
# Signing Transactions
Source: https://docs.initia.xyz/developers/developer-guides/tools/sdks/initia-js/transactions/signing-transactions
Sometimes, you may want to sign a transaction without broadcasting it. This is
useful in situations where you want to sign a transaction and then broadcast it
later. To showcase this, you will write a script that will sign a transaction,
compute the transaction hash from the signed transaction, and compare the
transaction hash to what you receive from broadcasting the transaction.
First, import the necessary classes and functions.
* `Coins`: A class that represents a list of
[Cosmos SDK coins](https://github.com/cosmos/cosmos-sdk/blob/main/types/coin.go).
* `Fee`: A class that's used to define the fee for a transaction.
* `RESTClient`: A class that represents a REST client.
* `MnemonicKey`: A class that's used to create a key from a mnemonic.
* `MsgSend`: A class that represents a message to send.
* `Wallet`: A class that represents a wallet.
```ts theme={null}
import {
Coins,
Fee,
RESTClient,
MnemonicKey,
MsgSend,
Wallet,
} from '@initia/initia.js'
import crypto from 'crypto'
```
Next, set up your environment variables. You will need the following:
* `mnemonic`: The mnemonic of the account that will be signing the transaction.
* `chainId`: The chain ID of the network you are working on.
* `restUrl`: The URL of the Initia REST.
* `gasPrices`: The gas prices for the transaction.
```ts theme={null}
const mnemonic = process.env.MNEMONIC
const chainId = process.env.CHAIN_ID || 'initiation-2'
const restUrl = process.env.REST_URL || 'https://rest.testnet.initia.xyz'
const gasPrices = process.env.GAS_PRICES || '0.015uinit' // Will be INIT for mainnet
```
You will also need to create a helper function to convert the signed transaction
data into a transaction hash hex string.
```ts theme={null}
export function getTxHash(tx: Uint8Array): string {
const s256Buffer = crypto
.createHash(`sha256`)
.update(Buffer.from(tx))
.digest()
const txbytes = new Uint8Array(s256Buffer)
return Buffer.from(txbytes.slice(0, 32)).toString(`hex`).toUpperCase()
}
```
Finally, create the main function to sign the transaction and compare the
transaction hash. Let's call this function `offlineSigningTest`.
To start, create two `RESTClient` instances. One that is connected to the
network, and one that is offline. You will use the offline REST client to sign
the transaction, and the online REST client to broadcast the transaction to
later compare.
```ts theme={null}
const offlineRestClient = new RESTClient(``, {
chainId: chainId,
gasPrices: gasPrices,
})
// rest client that is connected
const onlineRestClient = new RESTClient(restUrl, {
chainId: chainId,
gasPrices: gasPrices,
})
```
Next, generate the wallet client, as well as define the message, gas limit, and
fee for the transaction. You need to define the latter two because you will be
signing the transaction completely offline without interacting with the network
or any nodes.
```ts theme={null}
// set up key
const key = new MnemonicKey({
mnemonic: mnemonic,
})
const account = await onlineRestClient.auth.accountInfo(key.accAddress) // you have to know account number and current sequence
const wallet = new Wallet(offlineRestClient, key)
// msg to send
const msg = new MsgSend(key.accAddress, key.accAddress, '100uinit')
// use fixed fee to not estimate gas
const gasLimit = 500000
const feeAmount = new Coins(offlineRestClient.config.gasPrices)
.toArray()[0]
.mul(gasLimit)
const fee = new Fee(gasLimit, new Coins([feeAmount]))
```
Once you have all of that, create the transaction by calling
`wallet.createAndSignTx`. This function takes
* `msgs`: The message to send.
* `accountNumber`: The account number of the account that will be signing the
transaction.
* `sequence`: The sequence number of the account that will be signing the
transaction.
* `fee`: The fee for the transaction.
and returns a signed transaction object. Then convert the signed transaction
object to a byte array and compute the transaction hash using the helper
function created earlier.
```ts theme={null}
const signedTx = await wallet.createAndSignTx({
msgs: [msg],
accountNumber: account.getAccountNumber(),
sequence: account.getSequenceNumber(),
fee,
})
const signedTxBytes = signedTx.toBytes()
const txHash = getTxHash(signedTxBytes)
```
Finally, if you want to broadcast the transaction to the network later, you can
do so by using the `onlineRestClient` client. If you then retrieve the
transaction hash from the online REST client and compare it to the transaction
hash you computed earlier, you should see that they match.
```ts theme={null}
const broadcastRes = await onlineRestClient.tx.broadcastSync(signedTx)
// true
console.log(txHash === broadcastRes.txhash)
```
### Full Example
```ts src/signing-transaction.ts theme={null}
import {
Coins,
Fee,
RESTClient,
MnemonicKey,
MsgSend,
Wallet,
} from '@initia/initia.js'
import crypto from 'crypto'
const mnemonic = process.env.MNEMONIC
const chainId = process.env.CHAIN_ID || 'initiation-2'
const restUrl = process.env.REST_URL || 'https://rest.testnet.initia.xyz'
const gasPrices = process.env.GAS_PRICES || '0.015uinit' // Will be INIT for mainnet
export function getTxHash(tx: Uint8Array): string {
const s256Buffer = crypto
.createHash(`sha256`)
.update(Buffer.from(tx))
.digest()
const txbytes = new Uint8Array(s256Buffer)
return Buffer.from(txbytes.slice(0, 32)).toString(`hex`).toUpperCase()
}
async function offlineSigningTest() {
// rest client that is not connected
const offlineRestClient = new RESTClient(``, {
chainId: chainId,
gasPrices: gasPrices,
})
// rest client that is connected
const onlineRestClient = new RESTClient(restUrl, {
chainId: chainId,
gasPrices: gasPrices,
})
// set up key
const key = new MnemonicKey({
mnemonic: mnemonic,
})
const account = await onlineRestClient.auth.accountInfo(key.accAddress) // you have to know account number and current sequence
const wallet = new Wallet(offlineRestClient, key)
// msg to send
const msg = new MsgSend(key.accAddress, key.accAddress, '100uinit')
// use fixed fee to not estimate gas
const gasLimit = 500000
const feeAmount = new Coins(offlineRestClient.config.gasPrices)
.toArray()[0]
.mul(gasLimit)
const fee = new Fee(gasLimit, new Coins([feeAmount]))
const signedTx = await wallet.createAndSignTx({
msgs: [msg],
accountNumber: account.getAccountNumber(),
sequence: account.getSequenceNumber(),
fee,
})
const signedTxBytes = signedTx.toBytes()
const txHash = getTxHash(signedTxBytes)
const broadcastRes = await onlineRestClient.tx.broadcastSync(signedTx)
// true
console.log(txHash === broadcastRes.txhash)
}
offlineSigningTest()
```
# Address Format Conversion
Source: https://docs.initia.xyz/developers/developer-guides/vm-specific-tutorials/evm/address-conversion
[Tutorial GitHub Repository](https://github.com/initia-labs/examples/tree/main/evm/address-conversion)
This tutorial demonstrates how to convert between an EVM hex address and a
Cosmos bech32 address.
## Prerequisites
* [NodeJS](https://nodejs.org)
## Project Setup
First, create a new directory for your project.
```sh theme={null}
mkdir address-conversion
cd address-conversion
```
Next, initialize the project and install the `bech32-converting` package.
```sh theme={null}
npm init
npm install bech32-converting
```
Then create a new file called `index.js` in the `src` directory where you will
write your code.
<Note>
You can use any package that allows you to encode and decode bech32-prefixed
addresses. However, the specific steps for using those packages may vary.
</Note>
## Development
For this tutorial, assume that you have an EVM address
`0x0901aeeD1d5144987DaE3D95AB219ff75e9bA636` that you want to convert to a
Cosmos address, and then convert it back to an EVM address.
First, import the `bech32-converting` package and initialize the variable for
the chain's Bech32 prefix.
```js src/index.js theme={null}
const converter = require('bech32-converting')
let bech32Address = 'init1pyq6amga29zfsldw8k26kgvl7a0fhf3kftflmr'
```
### EVM Address to Cosmos Address
To convert an EVM address to a Cosmos address, use the `bech32-converting`
package's `toHex` function.
```js src/index.js theme={null}
const hexAddress = converter('init').toHex(bech32Address)
console.log(hexAddress) // 0x0901aeeD1d5144987DaE3D95AB219ff75e9bA636
```
### Cosmos Address to EVM Address
To convert a Cosmos address to an EVM address, use the `bech32-converting`
package's `fromHex` function.
```js src/index.js theme={null}
bech32Address = converter('init').toBech32(hexAddress)
console.log(bech32Address) // init1pyq6amga29zfsldw8k26kgvl7a0fhf3kftflmr
```
The full code for the script is then as follows:
```js src/index.js theme={null}
const converter = require('bech32-converting')
let bech32Address = 'init1pyq6amga29zfsldw8k26kgvl7a0fhf3kftflmr'
const hexAddress = converter('init').toHex(bech32Address)
console.log(hexAddress) // 0x0901aeeD1d5144987DaE3D95AB219ff75e9bA636
bech32Address = converter('init').toBech32(hexAddress)
console.log(bech32Address) // init1pyq6amga29zfsldw8k26kgvl7a0fhf3kftflmr
```
If you run this script, you should see the following output:
```sh theme={null}
0x0901aeeD1d5144987DaE3D95AB219ff75e9bA636
init1pyq6amga29zfsldw8k26kgvl7a0fhf3kftflmr
```
# Using Connect Oracle
Source: https://docs.initia.xyz/developers/developer-guides/vm-specific-tutorials/evm/connect-oracles
<Warning>
Compiling contracts that use
[ConnectOracle.sol](https://github.com/initia-labs/minievm/blob/main/x/evm/contracts/connect_oracle/ConnectOracle.sol)
requires the
[viaIR](https://soliditylang.org/blog/2024/07/12/a-closer-look-at-via-ir)
feature. For Foundry/Forge, this can be done by using the `--via-ir` flag. The
relevant methods for other tools may vary.
</Warning>
### 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
Create a new project directory and initialize it with `forge init`:
```sh theme={null}
mkdir connect-oracle
cd connect-oracle
forge init
```
## Implementing the Contract
Before writing the contract, first rename the template contract to `Oracle.sol`.
```sh theme={null}
mv src/Counter.sol src/Oracle.sol
```
Then update the contract from the template to be your oracle contract. Declare
the `IConnectOracle` interface, which will be used to interact with the
ConnectOracle contract.
```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;
```
Next, define the constructor for the contract. This will be used to initialize
the contract with the ConnectOracle contract address.
<Note>
The ConnectOracle contract is on MiniEVM precompiles. You can get its address by querying `${REST_URL}/minievm/evm/v1/connect_oracle` where `${REST_URL}` refers to the REST endpoint URL of the rollup.
```sh theme={null}
curl https://rest-evm-1.anvil.asia-southeast.initia.xyz/minievm/evm/v1/connect_oracle
```
The output will look like this:
```json theme={null}
{
"address": "0x031ECb63480983FD216D17BB6e1d393f3816b72F"
}
```
</Note>
```s프로젝트로 돌아가기