JSON-RPC 호출
Node API를 사용하면 직접 노드를 운영하지 않고 Klaytn의 다양한 JSON RPC API를 호출할 수 있으며, KIP-7, KIP-17 컨트랙트 조회 및 NFT 조회가 가능합니다.
JSON-RPC는 무상태, 경량 RPC(원격 프로시저 호출) 프로토콜로, HTTP 뿐 아니라 TCP, WebSocket 등을 통해 실행될 수 있습니다. JSON을 데이터 형식으로 사용합니다.
튜토리얼에 앞서
API 호출에 사용되는
x-chain-id
값은 8217(Cypress) 또는 1001(Baobab)입니다.API 호출에 필요한 필수 파라미터는 각 예시에 설명됩니다.
API 호출 시 사용자가 입력해야 하는 값은 중괄호 1개({}
)로 표시합니다. 사용자가 입력해야 하는 값은 아래 테이블과 같습니다.
chain-id
8217 또는 1001
Cypress(Klaytn 메인넷) 또는 Baobab(Klaytn 테스트넷)
access-key-id
인증 아이디
KAS 콘솔 - Security - Credential에서 발급받은 accessKeyId
secret-access-key
인증 비밀번호
KAS 콘솔 - Security - Credential에서 발급받은 secretAccessKey
krn
(optional) 계정 저장소의 ID
기본 계정 저장소 사용 시 불필요
API 인증 키가 있으면 모든 KAS 서비스를 사용할 수 있으며 Wallet API를 호출해 만든 Klaytn 계정에 대한 모든 권한을 소유합니다. 모든 권한에는 Klaytn 계정의 자산(KLAY 등) 이동이나 트랜잭션 전송 및 실행 권한이 포함됩니다. 만약 API 인증 키에 타인이 접근한다면 Klaytn 계정 권한을 탈취당해 원치 않는 트랜잭션이 발생할 수 있습니다.
KAS/Klaytn 계정 보안을 위해 KAS API 인증 키(Secret Access Key)를 타인과 함부로 공유하지 말고 주의해 관리하십시오.
이 예제에서는 Klaytn 계정 관리를 위한 API 몇 가지를 호출해보고 웹소켓 사용에 대해 설명하겠습니다.
가장 최근에 생성된 블록 번호 확인
Node API로 여러분 계정의 잔고, 계정 키 타입 등 계정에 관한 가장 최신 정보를 확인하려면 Klaytn상에 있는 가장 최신 블록의 블록 번호를 알아야합니다. 이를 위해 JSON-RPC 요청 { "method": "klay_blockNumber", "id": 1 }
을 보내고 최신의 블록 번호를 요청합니다.
API 호출
curl --location --request POST 'https://node-api.klaytnapi.com/v1/klaytn' \
-u {accessKeyId}:{secretAccessKey} \
--header 'x-chain-id: {chain-id}' \
--header 'Content-Type: application/json' \
--data-raw '{"jsonrpc":"2.0","method":"klay_blockNumber","params":[],"id":1}'
id
는 임의의 값입니다.params
,jsonrpc
는 생략 가능합니다.
API 응답
API가 성공적으로 실행되면 다음과 같은 응답을 받습니다.
{
"jsonrpc": "2.0",
"id": 1,
"result": "0x5d39"
}
result
는 16진수로 표현된 블록 번호값입니다.
Klaytn JSON-RPC API에 관한 더 자세한 내용은 다음을 확인하십시오. 이 API에 관한 자세한 내용은 다음을 확인하십시오. 이 문서 혹은 KAS에 관한 문의는 개발자 포럼을 방문해 도움 받으십시오.
EOA로 Klaytn 계정 정보 확인
API 호출
블록 번호와 Klaytn 계정 주소(EOA)를 입력하고 계정 정보를 조회하는 JSON-RPC 함수 klay_getAccount
를 실행합니다. klay_getAccount
는 주소(필수)와 블록번호/태그(필수 또는 선택) 파라미터를 받습니다. curl 등 HTTP 방식으로 직접 RPC를 호출할 경우 블록번호/태그는 필수 파라미터입니다.
curl --location --request POST 'https://node-api.klaytnapi.com/v1/klaytn' \
-u {accessKeyId}:{secretAccessKey} \
--header 'x-chain-id: {chain-id}' \
--header 'Content-Type: application/json' \
--data-raw '{"jsonrpc":"2.0","method":"klay_getAccount","params":["0x3111a0577f322e8fb54f78d9982a26ae7ca0f722", "0x5d39"],"id":1}'
id
는 임의의 값입니다.jsonrpc
는 생략 가능합니다.Klaytn 계정 주소값
0x3111a0577f322e8fb54f78d9982a26ae7ca0f722
은 예시값입니다.SDK(caver-js, caver-java)는 구현에 따라 블록번호/태그를 생략 가능합니다. 이 경우
"latest"
태그가 사용됩니다.
Node API는 매번 다른 Klaytn 엔드포인트 노드를 호출하며 블록 번호에 pending
을 입력할 경우 결과값이 기대와 다를 수 있습니다.
API 응답
API가 성공적으로 실행되면 다음과 같이 입력한 EOA를 가지고 있는 Klaytn 계정 정보를 나타내는 응답을 받습니다.
{
"jsonrpc": "2.0",
"id": 1,
"result": {
"accType": 1,
"account": {
"nonce": 4,
"balance": "0x8d286271f52600",
"humanReadable": false,
"key": {
"keyType": 1,
"key": {}
}
}
}
}
Klaytn JSON-RPC API에 관한 더 자세한 내용은 다음을 확인하십시오. 이 API에 관한 자세한 내용은 다음을 확인하십시오. 이 문서 혹은 KAS에 관한 문의는 개발자 포럼을 방문해 도움 받으십시오.
WebSocket 연결
WebSocket을 사용하면 특정 데이터를 얻기 위해 반복해서 요청을 할 필요없이 갱신된 결과를 받아올 수 있습니다. wscat과 같은 WebSocket 커맨드라인 툴을 설치해 사용해보세요.
WebSocket 연결을 위해서는 다음과 같이 요청을 보냅니다.
wscat -c wss://{accessKeyId}:{secretAccessKey}@node-api.klaytnapi.com/v1/ws/open?chain-id=1001
각 부분에 대한 설명은 다음과 같습니다:
{accessKeyId}와 {secretAccessKey}: API를 호출하는 주체가 KAS 회원이 맞는지 증명하는 API 인증 키입니다.
node-api.klaytnapi.com: Node API의 기본 URL입니다.
v1/ws/open: WebSocket 연결을 위한 엔드포인트입니다.
chain-id: 쿼리 파라미터로 전달되는 chain ID로, Baobab은 1001, Cypress는 8217입니다.
구독 API - klay_subscribe
WebSocket에 연결되었을 때 유의미하게 사용할 수 있는 것은 구독형(Subscription) API들로, 특정 이벤트를 감지하면서 새로운 데이터를 즉시 반환합니다. Klaytn의 경우 대표적으로 klay_subscribe
가 있습니다.
klay_subscribe
를 사용하면 특정 이벤트에 대한 구독을 생성합니다.
파라미터는 newHeads
또는 logs
로, newHeads
는 블록체인에 새로운 블록이 추가될 때마다 알림을 보내며, logs
는 새 블록에 추가된 로그들을 반환합니다.
요청 예시는 다음과 같습니다.
wscat -c http://localhost:8552
{"jsonrpc":"2.0", "id": 1, "method": "klay_subscribe", "params": ["newHeads"]}
응답은 아래와 같습니다.
< {"jsonrpc":"2.0","id":1,"result":"0xee42e843560a107c80fc7b241bb99e2a"} < {"jsonrpc":"2.0","method":"klay_subscription","params":{"subscription":"0xee42e843560a107c80fc7b241bb99e2a","result":{"parentHash":"0xb76aeee0d9cfd831be70c02ca00007debf2dfd0be511ddcf3230f9a9aaca7226","reward":"0xa86fd667c6a340c53cc5d796ba84dbe1f29cb2f7","stateRoot":"0xb249cabfea3601ee1f7aed542472510b0ffc495f964d227ca15190de6e5f9f1b","transactionsRoot":"0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470","receiptsRoot":"0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470","logsBloom":"0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000","blockScore":"0x1","number":"0x48c9863","gasUsed":"0x0","timestamp":"0x61a0392b","timestampFoS":"0x0","extraData":"0xd883010701846b6c617988676f312e31352e37856c696e757800000000000000f90164f85494571e53df607be97431a5bbefca1dffe5aef56f4d945cb1a7dccbd0dc446e3640898ede8820368554c89499fb17d324fa0e07f23b49d09028ac0919414db694b74ff9dea397fe9e231df545eb53fe2adf776cb2b841e69d51d827d04525c987b830666a2b901f5146fc89c6de0b053eda4b6ad843b50d74f7c71da7b1b0d912d230d04261d1132284ed0fc387794d669840afd4f01701f8c9b8412b84c3d3fcb6feed9ab4b089100b0fbdc0b7ac30306fc970fb7138b67d91ed3f7d6c2c3dd54c96257fdf2a1d0c89b46b9f13d7dd83a9f13f4c2524929485949500b841b72857a0912464986478ccce5fce5120bb84ce3e605e6867bf3140aee39dea821be908cf96b493e56cfdf70909e92ff26f953d9c558a6e8cd77867fce649129100b841462dc63b59d0026bbeac2c0543985a5aa168a69a669a7b9b92df342d63338cf80c032d06e93a1fae901824848f8d771e1635da9870a8f0e01ac4ab9194b8f8b801","governanceData":"0x","hash":"0x64ed8c397ed938d4f3134bc8ff3de1793534d2d4039e1c817941152a2bcc4d90"}}} < {"jsonrpc":"2.0","method":"klay_subscription","params":{"subscription":"0xee42e843560a107c80fc7b241bb99e2a","result":{"parentHash":"0x64ed8c397ed938d4f3134bc8ff3de1793534d2d4039e1c817941152a2bcc4d90","reward":"0xa86fd667c6a340c53cc5d796ba84dbe1f29cb2f7","stateRoot":"0x12c5511da5f3de8d0a528ffc34b3dcd24351ad8f0af7f6a84bba4896c7cb0156","transactionsRoot":"0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470","receiptsRoot":"0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470","logsBloom":"0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000","blockScore":"0x1","number":"0x48c9864","gasUsed":"0x0","timestamp":"0x61a0392c","timestampFoS":"0x0","extraData":"0xd883010701846b6c617988676f312e31352e37856c696e757800000000000000f90164f85494571e53df607be97431a5bbefca1dffe5aef56f4d945cb1a7dccbd0dc446e3640898ede8820368554c89499fb17d324fa0e07f23b49d09028ac0919414db694b74ff9dea397fe9e231df545eb53fe2adf776cb2b8418ef714aa58e3953b5fbfb11c6b4c8aa8959193109d38f18d2dbdf95a582b515f6050641cbc719507346fee59ed4d1cacfd314a1e04f4f216c92469e8c57135b501f8c9b841f6095016c67bfdd7ef688dcfcc4bac24e13e436a217567146a8bc672c0a80074109e742f6583a9fa6d4a1443972859fab817a0cfefabd63a0171c2d85490e45b00b84197da6c03d252aad50d926aba2302c694b18b054374737696bc47f4ae70f1a7d320fbb1f14e213c0e1f0d2f20ea634b73b3459dc5c315761bff4e8bc952cec89a01b84167fd68b3df42a86f12167bac56f283e02500ba6ff805a0083b94a2b40272a8673ab958563dbdf832ce5df79459f843868db1fe37b2bb97d7c967babb9ab54f4801","governanceData":"0x","hash":"0x5ac45a79fc99cbc4ae726775735547b7b6c5d8f5dbf229c8cbfe90a21ff5e98b"}}} ...
KAS에서 현재 지원하는 Node API 목록
위에서 안내한 방식으로 Klaytn의 다른 JSON-RPC API도 KAS에서 호출할 수 있습니다. 단, 현재 KAS는 일부 Node API만을 지원합니다. 현재 KAS에서 지원하는 Node API 목록은 아래와 같습니다.
Platform
Account
klay_isContractAccount
O
Platform
Account
klay_getTransactionCount
O
Platform
Account
klay_getCode
O
Platform
Account
klay_getBalance
O
Platform
Account
klay_getAccountKey
O
Platform
Account
klay_getAccount
O
Platform
Account
klay_accountCreated
O
Platform
Account
klay_encodeAccountKey
O
Platform
Account
klay_decodeAccountKey
O
Platform
Block
klay_syncing
O
Platform
Block
klay_getStorageAt
O
Platform
Block
klay_getCouncilSize
O
Platform
Block
klay_getCouncil
O
Platform
Block
klay_getCommitteeSize
O
Platform
Block
klay_getCommittee
O
Platform
Block
klay_getBlockWithConsensusInfoByNumber
O
Platform
Block
klay_getBlockWithConsensusInfoByHash
O
Platform
Block
klay_getBlockTransactionCountByNumber
O
Platform
Block
klay_getBlockTransactionCountByHash
O
Platform
Block
klay_getBlockReceipts
O
Platform
Block
klay_getBlockByNumber
O
Platform
Block
klay_getBlockByHash
O
Platform
Block
klay_blockNumber
O
Platform
Block
klay_getHeaderByNumber
O
Platform
Block
klay_maxPriorityFeePerGas
O
Platform
Configuration
klay_protocolVersion
O
Platform
Configuration
klay_gasPriceAt
O
Platform
Configuration
klay_gasPrice
O
Platform
Configuration
klay_clientVersion
O
Platform
Configuration
klay_chainID
O
Platform
Filter
klay_getLogs
O
Platform
Filter
klay_newFilter
O
Platform
Filter
klay_getFilterLogs
O
Platform
Miscellaneous
klay_sha3
O
Platform
Transaction
klay_sendRawTransaction
O
Platform
Transaction
klay_getTransactionReceipt
O
Platform
Transaction
klay_getTransactionByHash
O
Platform
Transaction
klay_getTransactionByBlockNumberAndIndex
O
Platform
Transaction
klay_getTransactionByBlockHashAndIndex
O
Platform
Transaction
klay_estimateGas
O
Platform
Transaction
klay_estimateComputationCost
O
Platform
Transaction
klay_call
O
Network
net
net_peerCountByType
O
Network
net
net_peerCount
O
Network
net
net_networkID
O
Network
net
net_listening
O
Platform
Account
klay_sign
X
Platform
Account
klay_accounts
X
Platform
Block
klay_mining
X
Platform
Filter
klay_uninstallFilter
X
Platform
Filter
klay_newPendingTransactionFilter
X
Platform
Filter
klay_newFilter
X
Platform
Filter
klay_newBlockFilter
X
Platform
Filter
klay_getFilterLogs
X
Platform
Filter
klay_getFilterChanges
X
Debug
Blockchain Inspection
debug_setHead
X
Debug
Blockchain Inspection
debug_printBlock
X
Debug
Blockchain Inspection
debug_preimage
X
Debug
Blockchain Inspection
debug_getModifiedAccountsByNumber
X
Debug
Blockchain Inspection
debug_getModifiedAccountsByHash
X
Debug
Blockchain Inspection
debug_getBlockRlp
X
Debug
Blockchain Inspection
debug_dumpBlock
X
Platform
Configuration
klay_writeThroughCaching
X
Platform
Configuration
klay_rewardbase
X
Platform
Configuration
klay_isSenderTxHashIndexingEnabled
X
Platform
Configuration
klay_isParallelDBWrite
X
Governance
Governance
governance_vote
X
Governance
Governance
governance_totalVotingPower
X
Governance
Governance
governance_showTally
X
Governance
Governance
governance_nodeAddress
X
Governance
Governance
governance_myVotingPower
X
Governance
Governance
governance_myVotes
X
Governance
Governance
governance_itemsAt
X
Governance
Governance
governance_chainConfig
X
Debug
Logging
debug_vmodule
X
Debug
Logging
debug_verbosity
X
Debug
Logging
debug_setVMLogTarget
X
Debug
Logging
debug_backtraceAt
X
service chain
Main-bridge
convertServiceChainBlockHashToMainChainTxHash
X
Debug
Profiling
debug_writeMemProfile
X
Debug
Profiling
debug_writeBlockProfile
X
Debug
Profiling
debug_stopPProf
X
Debug
Profiling
debug_stopCPUProfile
X
Debug
Profiling
debug_startPProf
X
Debug
Profiling
debug_startCPUProfile
X
Debug
Profiling
debug_setBlockProfileRate
X
Debug
Profiling
debug_isPProfRunning
X
Debug
Profiling
debug_cpuProfile
X
Debug
Profiling
debug_blockProfile
X
Debug
Runtime Debugging
debug_stacks
X
Debug
Runtime Debugging
debug_setGCPercent
X
Debug
Runtime Debugging
debug_metrics
X
Debug
Runtime Debugging
debug_memStats
X
Debug
Runtime Debugging
debug_gcStats
X
Debug
Runtime Debugging
debug_freeOSMemory
X
Debug
Runtime Tracing
debug_stopGoTrace
X
Debug
Runtime Tracing
debug_startGoTrace
X
Debug
Runtime Tracing
debug_goTrace
X
service chain
Sub-bridge
sendChainTxslimit
X
service chain
Sub-bridge
latestAnchoredBlockNumber
X
service chain
Sub-bridge
anchoring
X
Platform
Transaction
klay_signTransaction
X
Platform
Transaction
klay_sendTransaction
X
Platform
Transaction
klay_getTransactionReceiptBySenderTxHash
X
Platform
Transaction
klay_getTransactionBySenderTxHash
X
Platform
Transaction
klay_createAccessList
X
Platform
Gas
klay_feeHistory
X
Platform
Gas
klay_maxPriorityFeePerGas
X
Debug
VM Standard Tracing
debug_standardTraceBlockToFile
X
Debug
VM Standard Tracing
debug_standardTraceBadBlockToFile
X
Debug
VM Tracing
debug_traceTransaction
X
Debug
VM Tracing
debug_traceBlockFromFile
X
Debug
VM Tracing
debug_traceBlockByNumber
X
Debug
VM Tracing
debug_traceBlockByHash
X
Debug
VM Tracing
debug_traceBlock
X
Debug
VM Tracing
debug_traceBadBlock
X
Management
admin
admin_stopWS
X
Management
admin
admin_stopRPC
X
Management
admin
admin_startWS
X
Management
admin
admin_startRPC
X
Management
admin
admin_removePeer
X
Management
admin
admin_peers
X
Management
admin
admin_nodeInfo
X
Management
admin
admin_importChain
X
Management
admin
admin_exportChain
X
Management
admin
admin_datadir
X
Management
admin
admin_addPeer
X
service chain
service chain
removePeer
X
service chain
service chain
nodeInfo
X
service chain
service chain
addPeer
X
Management
personal
personal_unlockAccount
X
Management
personal
personal_sign
X
Management
personal
personal_sendValueTransfer
X
Management
personal
personal_sendTransaction
X
Management
personal
personal_sendAccountUpdate
X
Management
personal
personal_replaceRawKey
X
Management
personal
personal_newAccount
X
Management
personal
personal_lockAccount
X
Management
personal
personal_listAccounts
X
Management
personal
personal_importRawKey
X
Management
personal
personal_ecRecover
X
Management
txpool
txpool_status
X
Management
txpool
txpool_inspect
X
Management
txpool
txpool_content
X
이 API에 관한 자세한 내용은 다음을 확인하십시오. 이 문서 혹은 KAS에 관한 문의는 개발자 포럼을 방문해 도움 받으십시오.
Last updated
Was this helpful?