Skip to content

Instantly share code, notes, and snippets.

@giansalex
Last active March 6, 2023 05:01
Show Gist options
  • Save giansalex/50ddf9b9cad130d6d72b0a75b065b3f8 to your computer and use it in GitHub Desktop.
Save giansalex/50ddf9b9cad130d6d72b0a75b065b3f8 to your computer and use it in GitHub Desktop.
Parse Cosmwasm contract state.
const fs = require('fs');
// state.json -> GET /cosmwasm/wasm/v1/contract/{contract}/state
function main() {
const data = fs.readFileSync('cw721-state.json', 'utf8');
const state = JSON.parse(data);
const items = [];
state.models.forEach(m => {
items.push({
key: parseKey(m.key),
value: parseValue(m.value)
});
});
console.log(JSON.stringify(items, null, 2));
}
function parseKey(key) {
const data = Buffer.from(key, 'hex');
const keys = [];
let len, start;
for (let i = 0; i < data.length;) {
const val = data[i];
if (val === 0) {
len = data[i + 1];
start = i + 2;
} else {
len = data.length - i;
start = i;
}
i = start + len;
keys.push(data.subarray(start, i).toString('utf8'));
}
return keys;
}
function parseValue(value) {
const data = Buffer.from(value, 'base64');
return JSON.parse(data.toString('utf8'));
}
main();
{
"models": [
{
"key": "0006746F6B656E7330413243353836373344423634344645",
"value": "eyJvd25lciI6Imp1bm8xOTR2OHV3ZWUyZnZzMnM4ZmE1azdqMDNrdHdjODdoNXl5dm5hajQiLCJhcHByb3ZhbHMiOltdLCJ0b2tlbl91cmkiOiJpcGZzOi8vUW1WR1dYY3ZldkFSdXNZZkNmN0ZYcmNoRW9yNkZzd0RjZ2V0alZReWpuZnV1RSIsImV4dGVuc2lvbiI6bnVsbH0="
},
{
"key": "000D746F6B656E735F5F6F776E6572002B6A756E6F313934763875776565326676733273386661356B376A30336B747763383768357979766E616A3430413243353836373344423634344645",
"value": "MTY="
},
{
"key": "636F6E74726163745F696E666F",
"value": "eyJjb250cmFjdCI6ImNyYXRlcy5pbzpjdzcyMS1iYXNlIiwidmVyc2lvbiI6IjAuMTAuMSJ9"
},
{
"key": "6D696E746572",
"value": "Imp1bm8xOTR2OHV3ZWUyZnZzMnM4ZmE1azdqMDNrdHdjODdoNXl5dm5hajQi"
},
{
"key": "6E66745F696E666F",
"value": "eyJuYW1lIjoiTW9uZXRhIE5GVCIsInN5bWJvbCI6Ik1PTkVUQSJ9"
},
{
"key": "6E756D5F746F6B656E73",
"value": "MQ=="
}
],
"pagination": {
"next_key": null,
"total": "6"
}
}
[
{
"key":[
"tokens",
"0A2C58673DB644FE"
],
"value":{
"owner":"juno194v8uwee2fvs2s8fa5k7j03ktwc87h5yyvnaj4",
"approvals":[
],
"token_uri":"ipfs://QmVGWXcvevARusYfCf7FXrchEor6FswDcgetjVQyjnfuuE",
"extension":null
}
},
{
"key":[
"tokens__owner",
"juno194v8uwee2fvs2s8fa5k7j03ktwc87h5yyvnaj4",
"0A2C58673DB644FE"
],
"value":16
},
{
"key":[
"contract_info"
],
"value":{
"contract":"crates.io:cw721-base",
"version":"0.10.1"
}
},
{
"key":[
"minter"
],
"value":"juno194v8uwee2fvs2s8fa5k7j03ktwc87h5yyvnaj4"
},
{
"key":[
"nft_info"
],
"value":{
"name":"Moneta NFT",
"symbol":"MONETA"
}
},
{
"key":[
"num_tokens"
],
"value":1
}
]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment