### Wrapper File Example for Get Started Section Source: https://github.com/kaiachain/kaia-docs/blob/main/docs/_shared/README.md Create a wrapper file in the target section to import and render the shared content. This example shows the structure for the 'Get Started' section. ```mdx // docs/build/get-started/configure-wallet-for-kaia-networks.mdx --- id: wallet-config-get-started title: How to configure your wallet for Kaia Networks hide_title: true custom_edit_url: https://github.com/kaiachain/kaia-docs/blob/main/docs/_shared/configure-wallet-for-kaia-networks.mdx --- import SharedContent from '../../_shared/configure-wallet-for-kaia-networks.mdx'; ``` -------------------------------- ### Clone and Install ServiceChain Value Transfer Examples Source: https://github.com/kaiachain/kaia-docs/blob/main/docs/nodes/service-chain/quick-start/value-transfer.md Clone the example repository and install its dependencies to begin. ```bash $ git clone https://github.com/klaytn/servicechain-value-transfer-examples $ cd servicechain-value-transfer-examples $ npm install $ cd erc20 ``` -------------------------------- ### Install Dependencies for Kaia GA Example Source: https://github.com/kaiachain/kaia-docs/blob/main/docs/build/tutorials/ga-tutorial/ga-integration.md Sets up a new project directory, initializes npm, and installs necessary libraries including ethers-ext, ethers.js v6, and dotenv. ```bash mkdir kaia-ga-example cd kaia-ga-example npm init -y npm install --save @kaiachain/ethers-ext ethers@6 dotenv ``` -------------------------------- ### Execute HOMI Setup and Start SCN Source: https://github.com/kaiachain/kaia-docs/blob/main/docs/nodes/service-chain/install-service-chain.md Example commands to set up HOMI and start the Service Chain Consensus Node (SCN) after extracting the archive distribution. It also shows how to edit the configuration file. ```bash $ homi-darwin-amd64/bin/homi setup ... $ kscn-darwin-amd64/bin/kscnd start $ vi kscn-darwin-amd64/conf/kscnd.conf ``` -------------------------------- ### Start Kaia Node with Compression Enabled (Package Installation) Source: https://github.com/kaiachain/kaia-docs/blob/main/docs/misc/operation/optimize-storage.md Start your Kaia node after configuring the network. Compression is enabled by default in v2.1.0 and later. ```bash # Configure network in kend.conf sudo vi /etc/kend/conf/kend.conf # Set: NETWORK=mainnet or NETWORK=kairos # Start node (compression enabled by default in v2.1.0+) kend start # Verify kend status tail -f /var/kend/logs/kend.out ``` -------------------------------- ### Setup Node.js Project for Fee Delegation Source: https://github.com/kaiachain/kaia-docs/blob/main/docs/build/tutorials/fee-delegation-example.md Initialize a new Node.js project and install necessary packages, including @kaiachain/ethers-ext and ethers. This setup is recommended for Node.js version 22 or later. ```bash mkdir feedelegation_server cd feedelegation_server npm init -y npm install - -save @kaiachain/ethers-ext@^1.2.0 ethers@6 ``` -------------------------------- ### Clone and Install ElizaOS Source: https://github.com/kaiachain/kaia-docs/blob/main/docs/build/tools/kaia-agentkit/eliza.md Clone the ElizaOS repository, navigate to the directory, checkout the latest tag, install dependencies, and copy the example environment file. ```sh git clone https://github.com/elizaOS/eliza cd eliza git checkout $(git describe --tags --abbrev=0) pnpm install cp .env.example .env ``` -------------------------------- ### Full Kaia Safe API Kit Example Source: https://github.com/kaiachain/kaia-docs/blob/main/docs/build/wallets/kaia-safe/kaia-safe-api-kit.md A comprehensive example demonstrating the setup and usage of the Kaia Safe API Kit, including transaction creation, proposal, confirmation, and execution. ```javascript import SafeApiKit from '@safe-global/api-kit' import Safe from '@safe-global/protocol-kit' import { OperationType } from '@safe-global/safe-core-sdk-types' // https://chainlist.org/?search=kaia&testnets=true const RPC_URL = 'https://public-en-kairos.node.kaia.io' const SAFE_ADDRESS = ""; // 2 Owner Safe Address Ex: 0x123.... SAFE SHOULD const OWNER_1_ADDRESS = ""; // ONLY OWNER 1 and SAFE ADDRESS Need to have some test KAIA balance const OWNER_1_PRIVATE_KEY = ""; const OWNER_2_PRIVATE_KEY = ""; // OWNER 2 need not have any test KAIA const TO_ADDRESS = OWNER_1_ADDRESS; // Receiver address of sample transaction who receives 1 wei const apiKit = new SafeApiKit.default({ chainId: 1001n, txServiceUrl: 'https://docs-safe.kaia.io/txs-baobab/api' }) const protocolKitOwner1 = await Safe.default.init({ provider: RPC_URL, signer: OWNER_1_PRIVATE_KEY, safeAddress: SAFE_ADDRESS }) // 1. Create transaction const safeTransactionData = { to: TO_ADDRESS, value: '1', // 1 wei data: '0x', operation: OperationType.Call } const safeTransaction = await protocolKitOwner1.createTransaction({ transactions: [safeTransactionData] }) const safeTxHash = await protocolKitOwner1.getTransactionHash(safeTransaction) const signature = await protocolKitOwner1.signHash(safeTxHash) // 2. Propose transaction to the service try { await apiKit.proposeTransaction({ safeAddress: SAFE_ADDRESS, safeTransactionData: safeTransaction.data, safeTxHash, senderAddress: OWNER_1_ADDRESS, senderSignature: signature.data }) } catch(err) { console.log(err) } console.log("Transaction hash is "+safeTxHash) const transaction = await apiKit.getTransaction(safeTxHash) // const transactions = await service.getPendingTransactions() // const transactions = await service.getIncomingTransactions() // const transactions = await service.getMultisigTransactions() // const transactions = await service.getModuleTransactions() // const transactions = await service.getAllTransactions() // 3. Confirmation from Owner 2 const protocolKitOwner2 = await Safe.default.init({ provider: RPC_URL, signer: OWNER_2_PRIVATE_KEY, safeAddress: SAFE_ADDRESS }) const signature2 = await protocolKitOwner2.signHash(safeTxHash) // Confirm the Safe transaction const signatureResponse = await apiKit.confirmTransaction( safeTxHash, signature2.data ) console.log(signatureResponse) // 4. Execute transaction const safeTxn = await apiKit.getTransaction(safeTxHash); const executeTxReponse = await protocolKitOwner1.executeTransaction(safeTxn) const receipt = await executeTxReponse.transactionResponse?.wait(); console.log('Transaction executed:'); console.log(`https://kairos.kaiascan.io/tx/${receipt.hash}`) ``` -------------------------------- ### Genesis File Example Source: https://github.com/kaiachain/kaia-docs/blob/main/docs/nodes/service-chain/install-service-chain.md This is an example of a genesis file created by 'homi setup'. It includes chain configuration, timestamp, extra data, and initial account allocations. Remember to change the 'chainId' to prevent replay attacks. ```json { "config": { "chainId": 1000, "istanbul": { "epoch": 3600, "policy": 0, "sub": 22 }, "unitPrice": 0, "deriveShaImpl": 2, "governance": null }, "timestamp": "0x5dca0732", "extraData": "0x0000000000000000000000000000000000000000000000000000000000000000f85ad594f8690562c0839c44b17af421f7aaaa9f12dcc62bb8410000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000c0", "governanceData": null, "blockScore": "0x1", "alloc": { "f8690562c0839c44b17af421f7aaaa9f12dcc62b": { "balance": "0x2540be400" } }, "number": "0x0", "gasUsed": "0x0", "parentHash": "0x0000000000000000000000000000000000000000000000000000000000000000" } ``` -------------------------------- ### Run Development Server Source: https://github.com/kaiachain/kaia-docs/blob/main/docs/build/wallets/wallet-libraries/reown.md Command to start the development server for the Reown application. Ensure all dependencies are installed before running. ```bash npm run dev ``` -------------------------------- ### Clone Survey Mini dApp Project Source: https://github.com/kaiachain/kaia-docs/blob/main/docs/minidapps/survey-minidapp/intro.md Clone the example Survey Mini dApp project from GitHub to get started quickly. This command initializes the project locally. ```bash # clone project git clone https://github.com/kjeom/ExampleMiniDapp ``` -------------------------------- ### Setup Web3-Onboard with Chains and Wallets Source: https://github.com/kaiachain/kaia-docs/blob/main/docs/build/wallets/wallet-libraries/web3Onboard.md Instantiate Onboard with wallet modules, chain configurations (including Kaia Mainnet and Testnet), and application metadata. ```javascript import Onboard from "@web3-onboard/core"; const ETH_MAINNET_RPC_URL = `Paste ETH RPC URL`; const KAIA_MAINNET_URL = `Paste KAIA MAINNET URL` const KAIROS_TESTNET_URL = `Paste KAIROS TESTNET URL` const onboard = Onboard({ wallets: modules, // created in previous step chains: [ { id: "0x1", // chain ID must be in hexadecimal token: "ETH", namespace: "evm", label: "Ethereum Mainnet", rpcUrl: ETH_MAINNET_RPC_URL }, { id: "0x2019", // chain ID must be in hexadecimal token: "KAIA", namespace: "evm", label: "Kaia Mainnet", rpcUrl: KAIA_MAINNET_URL }, { id: "0x3e9", // chain ID must be in hexadecimel token: "KAIA", namespace: "evm", label: "Kairos Testnet", rpcUrl: KAIROS_TESTNET_URL }, // you can add as much supported chains as possible ], appMetadata: { name: "Kaia-web3-onboard-App", // change to your dApp name icon: "https://pbs.twimg.com/profile_images/1620693002149851137/GbBC5ZjI_400x400.jpg", // paste your icon logo: "https://pbs.twimg.com/profile_images/1620693002149851137/GbBC5ZjI_400x400.jpg", // paste your logo description: "Web3Onboard-Kaia", recommendedInjectedWallets: [ { name: "Coinbase", url: "https://wallet.coinbase.com/" }, { name: "MetaMask", url: "https://metamask.io" } ] } }); ``` -------------------------------- ### Setup Project Directory Source: https://github.com/kaiachain/kaia-docs/blob/main/docs/references/sdk/viem/viem.md Creates a new project directory and navigates into it. This is the initial step for setting up a new project using Viem. ```bash mkdir viem-example cd viem-example ``` -------------------------------- ### Create Project Directory and Navigate Source: https://github.com/kaiachain/kaia-docs/blob/main/docs/build/tools/kaia-agentkit/mcp.md Sets up a new directory for the project and changes into it. ```bash mkdir kaia-agentkit-mcp-example cd kaia-agentkit-mcp-example ``` -------------------------------- ### GET /api/balance Response Source: https://github.com/kaiachain/kaia-docs/blob/main/docs/build/tutorials/integrate-fee-delegation-service.md Example response from the `GET /api/balance` endpoint. 'data' is true if the balance is sufficient, false otherwise. ```json { "message": "Request was successful", "data": true, // true if sufficient balance, false if insufficient "status": true } ``` -------------------------------- ### Start Service Chain Node (SCN) Source: https://github.com/kaiachain/kaia-docs/blob/main/docs/nodes/service-chain/install-service-chain.md Commands to start the SCN service, depending on the installation method (RPM or Linux archive). ```bash ## when installed from rpm distribution systemctl start kscnd.service ``` ```bash ## when installed using linux archive kscnd start ``` -------------------------------- ### Set Up .env File Source: https://github.com/kaiachain/kaia-docs/blob/main/docs/build/tutorials/pyth-real-time-price.md Create a .env file in your project's root directory to store your private key. Remember to replace the placeholder with your actual private key. ```bash PRIVATE_KEY="0xDEAD....." // REPLACE WITH YOUR PRIVATE KEY ``` -------------------------------- ### Install and Configure Prometheus on macOS Source: https://github.com/kaiachain/kaia-docs/blob/main/docs/nodes/debugging/monitoring-setup.md Automates Prometheus installation, configuration, and PATH setup on macOS. Ensure to replace placeholders for IP and port. ```shell rm -rf prometheus echo "Installing Prometheus..." curl -LO https://github.com/prometheus/prometheus/releases/download/v2.43.0/prometheus-2.43.0.darwin-arm64.tar.gz tar xvfz prometheus-2.43.0.darwin-arm64.tar.gz > /dev/null 2>&1 && mv prometheus-2.43.0.darwin-arm64 prometheus && rm -rf prometheus-2.43.0.darwin-arm64 && rm -rf prometheus-2.43.0.darwin-arm64.tar.gz echo "export PATH=\"$HOMEDIR/monitoring/prometheus:\$PATH\"" >> ~/.bashrc && source ~/.bashrc # Generate Prometheus config file (prometheus.yml) printf "%s\n" "global:" \ " evaluation_interval: 15s" \ " scrape_interval: 15s" \ "" \ "scrape_configs:" \ "- job_name: klaytn" \ " static_configs:" \ " - targets:" > prometheus/prometheus.yml # Append target configurations for multiple nodes for (( i=0; i and with the actual IP address and port (61001) for each node printf " - \":%d\"\n" >> prometheus/prometheus.yml done ``` -------------------------------- ### Wrapper File Example for Wallet Configuration Section Source: https://github.com/kaiachain/kaia-docs/blob/main/docs/_shared/README.md This example demonstrates creating a wrapper file for the 'Wallet Configuration' section, importing and rendering the shared content. ```mdx // docs/build/wallets/wallet-config/configure-wallet-for-kaia-networks.mdx --- title: How to configure your wallet for Kaia Networks hide_title: true custom_edit_url: https://github.com/kaiachain/kaia-docs/blob/main/docs/_shared/configure-wallet-for-kaia-networks.mdx --- import SharedContent from '../../../_shared/configure-wallet-for-kaia-networks.mdx'; ``` -------------------------------- ### Install Web3Auth and Ethers.js Libraries Source: https://github.com/kaiachain/kaia-docs/blob/main/docs/build/wallets/wallet-libraries/web3Auth.mdx Install the necessary Web3Auth SDKs and ethers.js for interacting with the Kaia blockchain. This setup is required before proceeding with the integration. ```bash npm install --save @web3auth/modal @web3auth/base @web3auth/ethereum-provider @web3auth/default-evm-adapter npm install --save ethers ``` -------------------------------- ### Create Example Directory Source: https://github.com/kaiachain/kaia-docs/blob/main/docs/references/sdk/web3py-ext/getting-started.md Create a directory for your web3py-ext examples and navigate into it. ```bash > mkdir web3py-ext-examples & cd _$ ``` -------------------------------- ### Create Web3 Instance for QuickNode Source: https://github.com/kaiachain/kaia-docs/blob/main/docs/references/sdk/web3py-ext/fee-delegated-transaction/account-update.mdx Demonstrates how to switch the Web3 provider to a QuickNode endpoint. This allows for flexibility in choosing network access points. ```python w3 = Web3(Web3.HTTPProvider('YOUR_QUICKNODE_URL')) ``` -------------------------------- ### Run Submit Bid Example Source: https://github.com/kaiachain/kaia-docs/blob/main/docs/build/tutorials/mev-auction-sdk-guide.md Execute the submit bid example from the repository root. Ensure you have replaced your private key and checked TODO comments in the source code. ```bash # From repository root go run example/submitbid.go ``` -------------------------------- ### Node Key Example Source: https://github.com/kaiachain/kaia-docs/blob/main/docs/nodes/service-chain/install-service-chain.md This is an example of a node key file generated by 'homi setup'. This key is essential for node identification and communication within the network. ```text 0c28c77ce5c2ca9e495b860f190ed7dfe7bd5c1a2e5f816587eb4d3d9566df44 ``` -------------------------------- ### Smart Contract Deployment Example Source: https://github.com/kaiachain/kaia-docs/blob/main/docs/references/sdk/web3j-ext/basic-transaction/smart-contract-deploy.mdx This Java example demonstrates the complete process of deploying a smart contract on the Kaia network using Web3j. It covers connecting to the network, creating credentials, defining transaction parameters, signing, sending, and retrieving the transaction receipt. ```java import org.web3j.abi.FunctionEncoder; import org.web3j.abi.TypeReference; import org.web3j.abi.datatypes.Function; import org.web3j.abi.datatypes.generated.Uint256; import org.web3j.crypto.Credentials; import org.web3j.protocol.Web3j; import org.web3j.protocol.core.methods.response.TransactionReceipt; import org.web3j.tx.Contract; import org.web3j.tx.gas.ContractDeployer; import org.web3j.tx.gas.DefaultGasProvider; import org.web3j.utils.Numeric; import java.math.BigInteger; import static org.web3j.protocol.core.DefaultBlockParameterName.LATEST; public class SmartContractDeployExample { public static void main(String[] args) throws Exception { Web3j web3j = Web3j.build(new org.web3j.protocol.http.HttpService("https://public-enpoint.klaytnapi.com/v1/klaytn")); // https://public-enpoint.klaytnapi.com/v1/klaytn // Create KlayCredentials using the private key Credentials credentials = Credentials.create("0x1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d7e8f9a0b1c2d3e4f5a6b7c8d9e0f1a2b"); // Replace with your private key // Define gas price and gas limit for the transaction BigInteger gasPrice = BigInteger.valueOf(250000000000L); BigInteger gasLimit = BigInteger.valueOf(10000000); // Get the sender's address and current nonce String senderAddress = credentials.getAddress(); BigInteger nonce = web3j.ethGetTransactionCount(senderAddress, LATEST).send().getTransactionIndex(); // Define contract bytecode, you can get it from compiled solidity code String contractBytecode = "608060405234801561001057600080fd5b506004361061002b5760003560e01c8063cfae321714610030575b600080fd5b61003861004e565b60405161004591906100dc565b60405180910390f35b6000805461005b9061012a565b80601f01602080910402602001604051908101604052809291908181526020018280546100879061012a565b80156100d45780601f106100a9576101008083540402835291602001916100d4565b820191906000526020600020905b8154815290600101906020018083116100b757829003601f168201915b505050505081565b600060208083528351808285015260005b81811015610109578581018301518582016040015282016100ed565b506000604082860101526040601f19601f8301168501019250505092915050565b600181811c9082168061013e57607f821691505b60208210810361015e57634e487b7160e01b600052602260045260246000fd5b5091905056fea264697066735822122002272dad43feb87cde6d15be86d8d1af21672f2443deb524dce07ca0210d1cec64736f6c63430008120033"; // Get the chain ID from the Kaia network BigInteger chainId = web3j.ethChainId().send().getChainId(); // Initialize variables for transaction parameters String fromAddress = credentials.getAddress(); BigInteger value = BigInteger.ZERO; String toAddress = ""; // For contract deployment, 'to' is null String data = contractBytecode; // Create a raw transaction org.web3j.tx.RawTransaction rawTransaction = org.web3j.tx.RawTransaction.createContractTransaction( nonce, gasPrice, gasLimit, chainId, value, data ); // Sign the raw transaction using KlayRawTransaction.createTransaction byte[] signedMessage = org.web3j.crypto.TransactionEncoder.signMessage(rawTransaction, credentials); String txHash = Numeric.toHexString(signedMessage); // Send the transaction to kaia network org.web3j.protocol.core.methods.response.EthSendTransaction ethSendTransaction = web3j.ethSendRawTransaction(txHash).send(); String transactionHash = ethSendTransaction.getTransactionHash(); System.out.println("TxHash : \n" + transactionHash); // Get the transaction receipt and using the transaction hash TransactionReceipt ethReceipt = web3j.ethGetTransactionReceipt(transactionHash).send().getResult(); System.out.println("Receipt from eth_getTransactionReceipt : \n" + ethReceipt); TransactionReceipt receipt = web3j.klayGetTransactionReceipt(transactionHash).send().getResult(); System.out.println("Receipt from klay_getTransactionReceipt : \n" + receipt); web3j.shutdown(); TxTypeSmartContractDeploy rawTransactionDecoded = TxTypeSmartContractDeploy.decodeFromRawTransaction(signedMessage); System.out.println("TxType : " + rawTransactionDecoded.getKlayType()); } } ``` -------------------------------- ### Initialize Web3 Instance for QuickNode Source: https://github.com/kaiachain/kaia-docs/blob/main/docs/references/sdk/web3py-ext/fee-delegated-transaction/value-transfer-memo.mdx Alternatively, connect to a different provider like QuickNode by updating the Web3 instance's provider URL. ```python w3 = Web3(Web3.HTTPProvider('https://your-quicknode-url.com')) ``` -------------------------------- ### Fee Delegated Account Update Example Source: https://github.com/kaiachain/kaia-docs/blob/main/docs/references/sdk/web3j-ext/fee-delegated-transaction/account-update.mdx This Java example demonstrates how to perform a fee delegated account update using Web3j. It focuses on the setup and execution of such an update. ```java public class FeeDelegatedAccountUpdateExample { public static void main(String[] args) throws Exception { final Web3j web3j = Web3j.build(new HttpService("http://localhost:8545")); try { // Account update example String senderAddress = "0x0000000000000000000000000000000000000001"; String feePayerAddress = "0x0000000000000000000000000000000000000002"; String newAccountAddress = "0x0000000000000000000000000000000000000003"; String privateKey = "0x2a871d0798c4732857f2830704143071f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0"; // Create a fee delegated account update transaction FeeDelegatedAccountUpdate feeDelegatedAccountUpdate = new FeeDelegatedAccountUpdate( senderAddress, feePayerAddress, newAccountAddress, "0x", BigInteger.ONE, BigInteger.ONE, BigInteger.ONE, BigInteger.ONE, "0x", "0x" ); feeDelegatedAccountUpdate.sign(privateKey); // Send the transaction String txHash = web3j.ethSendTransaction(feeDelegatedAccountUpdate.toTransaction().toHex()).send().getTransactionHash(); System.out.println("Transaction hash: " + txHash); // Wait for transaction to be mined EthTransaction receipt = null; while (receipt == null || receipt.getTransaction().isEmpty()) { receipt = web3j.ethGetTransactionByHash(txHash).send(); Thread.sleep(1000); } // Decode the raw transaction to get the transaction type String txType = receipt.getTransaction().get().getRawTransaction().substring(0, 2); System.out.println("TxType : " + txType); } finally { web3j.shutdown(); } } } ``` -------------------------------- ### Initialize Web3 and Accounts Source: https://github.com/kaiachain/kaia-docs/blob/main/docs/references/sdk/web3js-ext/fee-delegated-transaction/smart-contract-deploy.mdx Set up the Web3 provider and create sender and fee payer accounts from private keys. ```javascript const feePayerAddr = "0xcb0eb737dfda52756495a5e08a9b37aab3b271da"; const feePayerPriv = "0x9435261ed483b6efa3886d6ad9f64c12078a0e28d8d80715c773e16fc000cff4"; const provider = new Web3.providers.HttpProvider("https://public-en-kairos.node.kaia.io"); const web3 = new Web3(provider); const senderAccount = web3.eth.accounts.privateKeyToAccount(senderPriv); const feePayerAccount = web3.eth.accounts.privateKeyToAccount(feePayerPriv); ``` -------------------------------- ### Value Transfer With Memo Example Source: https://github.com/kaiachain/kaia-docs/blob/main/docs/references/sdk/ethers-ext/v6/basic-transaction/value-transfer-memo.mdx This snippet shows a complete example of sending KAIA with a memo using Ethers.js v6. It includes all necessary setup and transaction logic. ```javascript const ethers = require("ethers"); const { Wallet, TxType, parseKlay } = require("@kaiachain/ethers-ext/v6"); const recieverAddr = "0xc40b6909eb7085590e1c26cb3becc25368e249e9"; const senderAddr = "0xa2a8854b1802d8cd5de631e690817c253d6a9153"; const senderPriv = "0x0e4ca6d38096ad99324de0dde108587e5d7c600165ae4cd6c2462c597458c2b8"; const provider = new ethers.JsonRpcProvider("https://public-en-kairos.node.kaia.io"); const wallet = new Wallet(senderPriv, provider); async function main() { const tx = { type: TxType.ValueTransferMemo, from: senderAddr, to: recieverAddr, value: parseKlay("0.01"), data: "0x1234567890", }; const sentTx = await wallet.sendTransaction(tx); console.log("sentTx", sentTx.hash); const receipt = await sentTx.wait(); console.log("receipt", receipt); } main(); ``` -------------------------------- ### Reloading Systemd Daemon After Installation Source: https://github.com/kaiachain/kaia-docs/blob/main/docs/misc/operation/troubleshooting.md Execute this command to reload the systemd manager configuration. This is necessary when a Kaia node fails to start with a 'Unit not found' error after installing the binary package. ```bash sudo systemctl daemon-reload ``` -------------------------------- ### Initialize Web3 Provider and Instance Source: https://github.com/kaiachain/kaia-docs/blob/main/docs/references/sdk/web3js-ext/account-management/keystore/keystoreV3.mdx Set up the HTTP provider and define a Web3 instance using the provider. This connects your application to the Kaia network. ```javascript const provider = new Web3.providers.HttpProvider( 'https://public-en-kairos.node.kaia.io' ) const web3 = new Web3(provider) ``` -------------------------------- ### Setup Provider and Wallet Instance with ethers-ext Source: https://github.com/kaiachain/kaia-docs/blob/main/docs/build/tutorials/how-to-send-usdt-tokens-using-kaia-sdk.md Configure the JsonRpcProvider for the Kaia network and instantiate a Wallet using a private key from environment variables. Ensure the recipient address and amount are correctly set. ```javascript import { ethers } from "ethers"; import { Wallet, JsonRpcProvider, parseKaiaUnits } from "@kaiachain/ethers-ext/v6"; import "dotenv/config"; const senderPriv = process.env.USDT_SENDER; const recipientAddress = "PASTE_RECIPIENT_ADDRESS" const amount = parseKaiaUnits("0.01", 6); const provider = new JsonRpcProvider("https://public-en.node.kaia.io"); const wallet = new Wallet(senderPriv, provider); ``` -------------------------------- ### Run the Agent Command Source: https://github.com/kaiachain/kaia-docs/blob/main/docs/build/tools/kaia-agentkit/langchain.md Execute this command in your terminal to start the AI agent after setup is complete. ```bash pnpm tsx agent.ts ``` -------------------------------- ### Example Deployment Output Source: https://github.com/kaiachain/kaia-docs/blob/main/docs/_shared/scaffold-eth.mdx This is an example of the output you can expect after successfully deploying a contract to a Kaia network. ```bash % yarn deploy ✔ Enter password to decrypt private key: Nothing to compile No need to generate any newer typings. deploying "YourContract" (tx: 0x90d0587fcbbfd34057c9bc8c77a3ae56807bcee20c19b278499ca5da70affbbb)...: deployed at 0xb1ea8476debb6d3021cC3a179B9eC21e01742d82 with 534186 gas 👋 Initial greeting: Building Unstoppable Apps!!! 📝 Updated TypeScript contract definition file on ../nextjs/contracts/deployedContracts.ts ``` -------------------------------- ### Setup Provider and Web3 Instance Source: https://github.com/kaiachain/kaia-docs/blob/main/docs/references/sdk/web3js-ext/account-management/keystore/keystoreV4-multi.mdx Configure the provider and initialize a Web3 instance. This is a prerequisite for interacting with the blockchain. ```javascript const provider = new Web3.providers.HttpProvider("https://public-en-ws.kaia.network"); const web3 = new Web3(provider); ``` -------------------------------- ### Install Web3-Onboard Core Source: https://github.com/kaiachain/kaia-docs/blob/main/docs/build/wallets/wallet-libraries/web3Onboard.md Install the core Web3-Onboard package using npm. ```bash npm i @web3-onboard/core ``` -------------------------------- ### GET /api/balance with API Key Source: https://github.com/kaiachain/kaia-docs/blob/main/docs/build/tutorials/integrate-fee-delegation-service.md Example of checking the balance with an API key. The balance must be greater than 0.1 KAIA. ```http GET /api/balance Authorization: Bearer your_api_key_here ``` -------------------------------- ### Unit Conversion Examples Source: https://github.com/kaiachain/kaia-docs/blob/main/docs/references/sdk/web3js-ext/utils/unit.mdx Demonstrates the usage of formatKlayUnits, formatKlay, and parseKlayUnits for converting between different Kaia units. Ensure you have @kaiachain/web3js-ext installed. ```javascript const { formatKlay, parseKlay, formatKlayUnits, } = require('@kaiachain/web3js-ext') async function main() { console.log( 'example basefee in ston =', formatKlayUnits('0x5d21dba00', 'ston') ) console.log('transfer amount in klay =', formatKlay('1230000000000000000')) console.log( 'example gas price in peb =', parseKlayUnits('50', 'ston').toString() ) console.log('transfer amount in peb =', parseKlay('9.87').toString()) } main() ``` ```zsh ❯ node unitUtils.js example basefee in ston = 25.0 transfer amount in klay = 1.23 example gas price in peb = 50000000000 transfer amount in peb = 9870000000000000000 ``` -------------------------------- ### Fetch ETH/USDT Price with ethers.js Source: https://github.com/kaiachain/kaia-docs/blob/main/docs/build/tools/oracles/supraoracles.md This example demonstrates how to get the ETH/USDT price using ethers.js. It supports both ethers v6.0 and older versions (<= 5.7.2). ```javascript // example assumes that the ethers library has been imported and is accessible within your scope const getEthUsdtPrice = async () => { ////for ethers version 6.0 const provider = new ethers.JsonRpcProvider("https://public-en-kairos.node.kaia.io") ////for ethers version <= 5.7.2 //const provider = new ethers.providers.JsonRpcProvider('https://public-en-kairos.node.kaia.io') const abi = [{ "inputs": [ { "internalType": "string", "name": "marketPair", "type": "string" } ], "name": "checkPrice", "outputs": [ { "internalType": "int256", "name": "price", "type": "int256" }, { "internalType": "uint256", "name": "timestamp", "type": "uint256" } ], "stateMutability": "view", "type": "function" } ] const address = '0x7f003178060af3904b8b70fEa066AEE28e85043E' const sValueFeed = new ethers.Contract(address, abi, provider) const price = (await sValueFeed.checkPrice('eth_usdt')).price console.log(`The price is: ${price.toString()}`) } getEthUsdtPrice() ``` -------------------------------- ### Import and Setup Wallets for Fee-Delegated Smart Contract Deploy Source: https://github.com/kaiachain/kaia-docs/blob/main/docs/references/sdk/viem-ext/fee-delegated-transaction/smart-contract-deploy.mdx Import necessary modules from '@kaiachain/viem-ext' and set up sender and fee payer wallets. Ensure wallets are configured with the Kairos chain, HTTP transport, and private keys. ```js import { http, createWalletClient, kairos, TxType, privateKeyToAccount } from "@kaiachain/viem-ext"; const senderWallet = createWalletClient({ chain: kairos, transport: http(), account: privateKeyToAccount( "0x0e4ca6d38096ad99324de0dde108587e5d7c600165ae4cd6c2462c597458c2b8" ) }) const feePayerWallet = createWalletClient({ chain: kairos, transport: http(), account: privateKeyToAccount( "0x9435261ed483b6efa3886d6ad9f64c12078a0e28d8d80715c773e16fc000cff4" ) }); ``` -------------------------------- ### Initialize Web3 Instance for Kaia Testnet Source: https://github.com/kaiachain/kaia-docs/blob/main/docs/references/sdk/web3py-ext/account-management/account-key/multisig.mdx Create a Web3 instance connected to the Kaia testnet using the provided provider URL. Alternatively, you can switch to a different provider like QuickNode. ```python w3 = Web3(Web3.HTTPProvider( 'https://public-en-kairos.node.kaia.io' )) ``` -------------------------------- ### Get Updated Counter Number Source: https://github.com/kaiachain/kaia-docs/blob/main/docs/references/sdk/ethers-ext/v6/smart-contract/write-with-fee-delegation.mdx After a transaction, retrieve the updated value of a counter using the `counter.number()` method. This example shows how to fetch and display the new value. ```javascript const number = await counter.number(); console.log(`number after ${number}`); ``` -------------------------------- ### GET /api/balance without API Key Source: https://github.com/kaiachain/kaia-docs/blob/main/docs/build/tutorials/integrate-fee-delegation-service.md Example of checking the balance using an address when no API key is provided. The balance must be greater than 0.1 KAIA. ```http GET /api/balance?address=0x742d35Cc6634C0532925a3b8D2A4DDDeAe0e4Cd3 ``` -------------------------------- ### Install and Initialize Foundry Source: https://github.com/kaiachain/kaia-docs/blob/main/docs/_shared/create-and-manage-wallets-securely.md Installs Foundry and initializes a new project. Use this to set up your development environment. ```bash curl -L https://foundry.paradigm.xyz | bash ``` ```bash foundryup forge init foundry-encrypted cd foundry-encrypted ``` -------------------------------- ### Initialize Hardhat Project Source: https://github.com/kaiachain/kaia-docs/blob/main/docs/minidapps/survey-minidapp/quickstart.md Bootstrap a sample Hardhat project. Select a TypeScript project when prompted. ```bash npx hardhat init ``` -------------------------------- ### Running the Fee Payer Server Source: https://github.com/kaiachain/kaia-docs/blob/main/docs/build/tutorials/fee-delegation-example.md This bash command starts the fee payer server using Node.js. Ensure you have Node.js installed and the `feepayer_server.js` file is in your current directory. ```bash node feepayer_server.js // output Fee delegate service started ... ``` -------------------------------- ### Install Prometheus Binaries on Linux Source: https://github.com/kaiachain/kaia-docs/blob/main/docs/nodes/debugging/monitoring-setup.md Extract the downloaded Prometheus archive and move the 'prometheus' and 'promtool' binaries to your system's PATH. This example assumes a Linux environment. ```bash wget https://github.com/prometheus/prometheus/releases/download/v2.53.3/prometheus-2.53.3.linux-amd64.tar.gz tar xvfz prometheus-2.53.3.linux-amd64.tar.gz mv prometheus-2.53.3.linux-amd64/prometheus /usr/local/bin/ mv prometheus-2.53.3.linux-amd64/promtool /usr/local/bin/ ``` -------------------------------- ### Gasless Transaction Setup and Execution Source: https://github.com/kaiachain/kaia-docs/blob/main/docs/references/sdk/ethers-ext/v6/gas-abstraction/gasless.mdx This snippet shows the complete process of setting up a gasless transaction. It includes initializing the wallet, querying token details, checking router support, calculating necessary amounts for swaps, and sending ApproveTx and SwapTx. Use this for a full-fledged gasless transaction implementation. ```javascript const ethers = require("ethers"); const { Wallet, gasless } = require("@kaiachain/ethers-ext/v6"); // Replace with ERC20 token address to be spent const tokenAddr = "0xcB00BA2cAb67A3771f9ca1Fa48FDa8881B457750"; // Kairos:TEST token // Replace with your wallet address and private key const senderAddr = "0xa0Ee7A142d267C1f36714E4a8F75612F20a79720"; const senderPriv = "0x2a871d0798f97d79848a013d4936a73bf4cc922c825d33c1cf7073dff6d409c6"; const provider = new ethers.JsonRpcProvider("https://public-en-kairos.node.kaia.io"); const wallet = new Wallet(senderPriv, provider); const ERC20_ABI = [ "function decimals() view returns (uint8)", "function symbol() view returns (string)", "function allowance(address owner, address spender) view returns (uint256)", "function balanceOf(address owner) view returns (uint256)" ]; // senderAddr wants to swap the ERC20 token for at least 0.01 KAIA so she can execute the AppTx. async function main() { const appTxFee = ethers.parseEther("0.01").toString(); // Query the environment console.log(`Using token at address: ${tokenAddr}`); const token = new ethers.Contract(tokenAddr, ERC20_ABI, provider); const tokenSymbol = await token.symbol(); const tokenDecimals = await token.decimals(); const tokenBalance = await token.balanceOf(senderAddr); console.log(`\nInitial balance of the sender ${senderAddr}`); console.log(`- ${ethers.formatEther(await provider.getBalance(senderAddr))} KAIA`); console.log(`- ${ethers.formatUnits(tokenBalance, tokenDecimals)} ${tokenSymbol}`); const router = await gasless.getGaslessSwapRouter(provider); const routerAddr = await router.getAddress(); const isTokenSupported = await router.isTokenSupported(tokenAddr); const commissionRate = Number(await router.commissionRate()); console.log(`\nGaslessSwapRouter address: ${routerAddr}`); console.log(`- The token is supported: ${isTokenSupported}`); console.log(`- Commission rate: ${commissionRate} bps`); // If sender hasn't approved, include ApproveTx first. const allowance = await token.allowance(senderAddr, routerAddr); const approveRequired = (allowance == 0n); const txs = []; if (approveRequired) { console.log("\nAdding ApproveTx because allowance is 0"); const approveTx = await gasless.getApproveTx( provider, senderAddr, tokenAddr, routerAddr, gasPrice, ); txs.push(approveTx); } else { console.log("\nNo ApproveTx needed"); } // - amountRepay (KAIA) is the cost of LendTx, ApproveTx, and SwapTx. The block miner shall fund it first, // then the sender has to repay from the swap output. // - minAmountOut (KAIA) is the required amount of the swap output. It must be enough to cover the amountRepay // and pay the commission, still leaving appTxFee. // - amountIn (token) is the amount of the token to be swapped to produce minAmountOut plus slippage. console.log("\nCalculating the amount of the token to be swapped..."); const gasPrice = Number((await provider.getFeeData()).gasPrice); console.log(`- gasPrice: ${ethers.formatUnits(gasPrice, "gwei")} gkei`); const amountRepay = gasless.getAmountRepay(approveRequired, gasPrice); console.log(`- amountRepay: ${ethers.formatEther(amountRepay)} KAIA`); const minAmountOut = gasless.getMinAmountOut(amountRepay, appTxFee, commissionRate); console.log(`- minAmountOut: ${ethers.formatEther(minAmountOut)} KAIA`); const slippageBps = 50 // 0.5% const amountIn = await gasless.getAmountIn(router, tokenAddr, minAmountOut, slippageBps); console.log(`- amountIn: ${ethers.formatUnits(amountIn, tokenDecimals)} ${tokenSymbol}`); if (tokenBalance < amountIn) { console.log(`\nInsufficient balance of the token: ${ethers.formatUnits(tokenBalance, tokenDecimals)} ${tokenSymbol}`); console.log(`- Please transfer more ${tokenSymbol} to the sender ${senderAddr}`); return; } const swapTx = await gasless.getSwapTx( provider, senderAddr, tokenAddr, routerAddr, amountIn, minAmountOut, amountRepay, gasPrice, approveRequired, ); txs.push(swapTx); console.log("\nSending transactions..."); const sentTxs = await wallet.sendTransactions(txs); for (const tx of sentTxs) { console.log(`- Tx sent: (nonce: ${tx.nonce}) ${tx.hash}`); } console.log("\nWaiting for transactions to be mined..."); let blockNum = 0; for (const sentTx of sentTxs) { const receipt = await sentTx.wait(); console.log(`- Tx mined at block ${receipt.blockNumber}`); blockNum = receipt.blockNumber; } console.log("\nListing the block's transactions related to the sender..."); const block = await provider.getBlock(blockNum, true); ``` -------------------------------- ### Setup Wallet Client and Account with Viem Source: https://github.com/kaiachain/kaia-docs/blob/main/docs/references/sdk/viem/viem.md Sets up a wallet client for performing actions that require an account, such as signing transactions. It requires chain, transport, and account details. ```typescript import { createWalletClient } from 'viem' import { privateKeyToAccount } from 'viem/accounts' const walletClient = createWalletClient({ chain: klaytnBaobab, transport: http("https://public-en-kairos.node.kaia.io") }) const account = privateKeyToAccount("PASTE PRIVATE KEY HERE"); ``` -------------------------------- ### Install Prometheus Binaries on macOS Source: https://github.com/kaiachain/kaia-docs/blob/main/docs/nodes/debugging/monitoring-setup.md Extract the downloaded Prometheus archive and move the 'prometheus' and 'promtool' binaries to your system's PATH. This example assumes a macOS environment. ```bash tar xvfz prometheus-2.53.3.darwin-arm64.tar.gz mv prometheus-2.53.3.darwin-arm64/prometheus /usr/local/bin/ mv prometheus-2.53.3.darwin-arm64/promtool /usr/local/bin/ ``` -------------------------------- ### Ken Init Command Help Source: https://github.com/kaiachain/kaia-docs/blob/main/docs/nodes/endpoint-node/ken-cli-commands.md Shows help for the 'ken init' command, which initializes a new genesis block and network definition. ```bash ken init -h init [command options] [arguments...] The init command initializes a new genesis block and definition for the network. This is a destructive action and changes the network in which you will be participating. ... ```