Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

get vbank asset info from chain registry #40

Draft
wants to merge 6 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .gitmodules
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
[submodule "src/lib/chain-registry"]
path = src/lib/chain-registry
url = https://github.com/cosmos/chain-registry
163 changes: 163 additions & 0 deletions src/lib/bulk-asset.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,163 @@
#!/bin/env tsx
import { createRequire } from 'module';
import fs from 'fs';
import path from 'path';
import crypto from 'crypto';
import { makeFileReader } from './fs.ts';

const nodeRequire = createRequire(import.meta.url);
const asset = {
registry: nodeRequire.resolve('./chain-registry/README.md'),
};

type Rd = ReturnType<typeof makeFileReader>;

const getJSON = async (rd: Rd) => {
const txt = await rd.readText();
return JSON.parse(txt);
};

const getIBCChannels = async (rd: Rd) => {
const ibc = rd.neighbor('./_IBC/');
const channels = await ibc.children();
return { ibc, channels };
};

type ChainInfo = {
chain_name: string;
client_id: string;
connection_id: string;
};

type ChannelInfo = {
channel_id: string;
port_id: string;
client_id?: string;
connection_id?: string;
};

type ConnectionInfo = {
['$schema']: string;
chain_1: ChainInfo;
chain_2: ChainInfo;
channels: Array<{
chain_1: ChannelInfo;
chain_2: ChannelInfo;
ordering: 'ordered' | 'unordered';
version: string;
tags?: {
status?: 'live' | 'upcoming' | 'killed';
preferred?: boolean;
};
}>;
};

const getIBCNeighbors = async (rd: Rd, name: string) => {
const { ibc, channels } = await getIBCChannels(rd);
const found = channels.filter(
ch => ibc.relative(ch.toString()).includes(name) // TODO word boundaries only
);
// console.log(found.map(r => ibc.relative(r.toString())));

return Promise.all(found.map(ch => getJSON(ch) as Promise<ConnectionInfo>));
};

type InterchainAssetParams = {
denom: string;
decimalPlaces: number;
issuerName: string;
};

const x = () => {

Check failure on line 71 in src/lib/bulk-asset.ts

View workflow job for this annotation

GitHub Actions / unit

'x' is declared but its value is never read.
const p: InterchainAssetParams = {
decimalPlaces: 6,
denom: '@@@',
issuerName: 'whee',
};
return p;
};

type DenomUnit = { denom: string; exponent: number };

type AssetT = {
denom_units: DenomUnit[];
base: string;
display: string;
name: string;
symbol: string;
description?: string;
};

type AssetList = {
chain_name: string;
assets: AssetT[];
};

export const pprint = (x: unknown) => JSON.stringify(x, null, 2);

const assetInfo = (a: AssetT) => {
const { symbol: allegedName, denom_units } = a;
const decimalPlaces = denom_units.find(u => u.denom === a.display)?.exponent;
const assetKind = typeof decimalPlaces === 'number' ? 'nat' : undefined;
// if (decimalPlaces === undefined) console.log('@@@', pprint(a));
return {
allegedName,
assetKind,
decimalPlaces,
};
};

const chainInfo = async (rd: Rd, name: string) => {
const chain = await getJSON(rd.neighbor(`./${name}/chain.json`));
const assetlist: AssetList = await getJSON(
rd.neighbor(`./${name}/assetlist.json`)
);
return { chain, assetlist };
};

const sha256 = (txt: string) =>
crypto.createHash('sha256').update(txt).digest('hex');

const main = async (src = 'agoric') => {
// console.log('asset paths', asset);
const rd = makeFileReader(asset.registry, { fs, path }).neighbor('../');
// console.log('chain registry rd', `${rd}`);
// console.log('chains', `${await rd.children()}`);

const agChannels = await getIBCNeighbors(rd, src);

for await (const peer of agChannels) {
if (peer.chain_1.chain_name !== src) throw Error(pprint(peer));
const { chain_2, channels } = peer;
// if (!['osmosis', 'cosmoshub'].includes(chain_2.chain_name)) continue; // XXX
// console.log(pprint(chan));
const other = await chainInfo(rd, chain_2.chain_name);
for (const chan of channels) {
const { channel_id, port_id } = chan.chain_1;
if (port_id !== 'transfer') continue;

for (const asset of other.assetlist.assets) {
const info = assetInfo(asset);
const path = `${port_id}/${channel_id}/${asset.base}`;
const hash = sha256(path).toUpperCase();
const denom = `ibc/${hash}`;
if (info.decimalPlaces === undefined) continue;
const ia: InterchainAssetParams = {
decimalPlaces: info.decimalPlaces,
denom,
issuerName: asset.symbol,
};
console.log(
`${src}-${channel_id}->${chain_2.chain_name} $${asset.symbol}`,
path,
ia
);
}
}
}
};

main().catch(err => {
console.error(err);
process.exit(1);
});
1 change: 1 addition & 0 deletions src/lib/chain-registry
Submodule chain-registry added at 394a64
154 changes: 154 additions & 0 deletions src/lib/fs.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,154 @@
import * as fsT from 'fs';
import * as fspT from 'fs/promises';
import * as pathT from 'path';

const { freeze } = Object;

let mutex = Promise.resolve(undefined);

export const makeFileReader = (
fileName: string,
{
fs,
path,
}: {
fs: {
promises: Pick<typeof fspT, 'readFile' | 'stat' | 'readdir'>;
};
path: Pick<typeof pathT, 'resolve' | 'relative' | 'normalize'>;
}
) => {
const make = (there: string) => makeFileReader(there, { fs, path });

// fs.promises.exists isn't implemented in Node.js apparently because it's pure
// sugar.
const exists = (fn: string) =>
fs.promises.stat(fn).then(
() => true,
e => {
if (e.code === 'ENOENT') {
return false;
}
throw e;
}
);

const readText = async () => {
const promise = mutex;
let release = Function.prototype;
mutex = new Promise(resolve => {
release = resolve;
});
await promise;
try {
return await fs.promises.readFile(fileName, 'utf-8');
} finally {
release(undefined);
}
};

const maybeReadText = () =>
readText().catch(error => {
if (
error.message.startsWith('ENOENT: ') ||
error.message.startsWith('EISDIR: ')
) {
return undefined;
}
throw error;
});

const neighbor = (ref: string) => make(path.resolve(fileName, ref));
return freeze({
toString: () => fileName,
readText,
maybeReadText,
neighbor,
stat: () => fs.promises.stat(fileName),
absolute: () => path.normalize(fileName),
relative: (there: string) => path.relative(fileName, there),
exists: () => exists(fileName),
children: () =>
fs.promises.readdir(fileName).then(refs => refs.map(neighbor)),
});
};

export const makeFileWriter = (
fileName: string,
{
fs,
path,
}: {
fs: Pick<typeof fsT, 'existsSync'> & {
promises: Pick<
typeof fspT,
'readFile' | 'stat' | 'writeFile' | 'mkdir' | 'rm' | 'rename'
>;
};
path: Pick<typeof pathT, 'resolve' | 'relative' | 'normalize' | 'dirname'>;
},
make = (there: string) => makeFileWriter(there, { fs, path }, make)
) => {
const writeText = async (txt: string, opts: object) => {
const promise = mutex;
let release = Function.prototype;
mutex = new Promise(resolve => {
release = resolve;
});
await promise;
try {
return await fs.promises.writeFile(fileName, txt, opts);
} finally {
release(undefined);
}
};

return freeze({
toString: () => fileName,
writeText,
readOnly: () => makeFileReader(fileName, { fs, path }),

Check failure on line 109 in src/lib/fs.ts

View workflow job for this annotation

GitHub Actions / unit

Type 'Pick<typeof import("fs"), "existsSync"> & { promises: Pick<typeof import("fs/promises"), "readFile" | "stat" | "rename" | "rm" | "mkdir" | "writeFile">; }' is not assignable to type '{ promises: Pick<typeof import("fs/promises"), "readFile" | "stat" | "readdir">; }'.
neighbor: (ref: string) => make(path.resolve(fileName, ref)),
mkdir: (opts: object) => fs.promises.mkdir(fileName, opts),
rm: (opts: object) => fs.promises.rm(fileName, opts),
rename: (newName: string) =>
fs.promises.rename(
fileName,
path.resolve(path.dirname(fileName), newName)
),
});
};

export const makeAtomicFileWriter = (
fileName: string,
{
fs,
path,
}: {
fs: Pick<typeof fsT, 'existsSync'> & {
promises: Pick<
typeof fspT,
'readFile' | 'stat' | 'writeFile' | 'mkdir' | 'rm' | 'rename'
>;
};
path: Pick<typeof pathT, 'resolve' | 'relative' | 'normalize' | 'dirname'>;
},
pid: number | undefined = undefined,
nonce: number | undefined = undefined,
make = (there: string) =>
makeAtomicFileWriter(there, { fs, path }, pid, nonce, make)
) => {
const writer = makeFileWriter(fileName, { fs, path }, make);
return freeze({
...writer,
atomicWriteText: async (txt: string, opts: object) => {
const scratchName = `${fileName}.${nonce || 'no-nonce'}.${
pid || 'no-pid'
}.scratch`;
const scratchWriter = writer.neighbor(scratchName);
await scratchWriter.writeText(txt, opts);
const stats = await scratchWriter.readOnly().stat();
await scratchWriter.rename(fileName);
return stats;
},
});
};
Loading