Setup eslint and husky pre-commit (#3)

* Set up eslint and husky

* Fix eslint errors

---------

Co-authored-by: neeraj <neeraj.rtly@gmail.com>
This commit is contained in:
Nabarun Gogoi 2024-03-07 09:47:05 +05:30 committed by GitHub
parent f2401e6953
commit de0ac597a1
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
27 changed files with 2009 additions and 661 deletions

5
.eslintignore Normal file
View File

@ -0,0 +1,5 @@
# Don't lint node_modules.
node_modules
# Don't lint build output.
dist

29
.eslintrc.json Normal file
View File

@ -0,0 +1,29 @@
{
"env": {
"browser": true,
"es2021": true
},
"extends": [
"semistandard",
"plugin:@typescript-eslint/recommended"
],
"parser": "@typescript-eslint/parser",
"parserOptions": {
"ecmaVersion": 12,
"sourceType": "module"
},
"plugins": [
"@typescript-eslint"
],
"rules": {
// TODO: Remove after resolution
"indent": ["error", 2, { "SwitchCase": 1 }],
"@typescript-eslint/no-explicit-any": "off",
"@typescript-eslint/no-unused-vars": "off",
"prefer-const": "off",
"@typescript-eslint/no-empty-function": "off",
"@typescript-eslint/ban-ts-comment": "off",
"camelcase": "off",
"@typescript-eslint/ban-types": "off"
}
}

1
.husky/pre-commit Normal file
View File

@ -0,0 +1 @@
yarn lint

View File

@ -2,5 +2,5 @@
module.exports = {
preset: 'ts-jest',
testEnvironment: 'node',
setupFiles: ["dotenv/config"]
setupFiles: ['dotenv/config']
};

View File

@ -11,8 +11,18 @@
"@types/lodash": "^4.14.181",
"@types/semver": "^7.3.9",
"@types/tiny-secp256k1": "1.0.0",
"@typescript-eslint/eslint-plugin": "^5.47.1",
"@typescript-eslint/parser": "^5.47.1",
"dotenv": "^16.0.0",
"eslint": "^8.35.0",
"eslint-config-semistandard": "^15.0.1",
"eslint-config-standard": "^16.0.3",
"eslint-plugin-import": "^2.27.5",
"eslint-plugin-node": "^11.1.0",
"eslint-plugin-promise": "^5.1.0",
"eslint-plugin-standard": "^5.0.0",
"google-protobuf": "^3.21.0",
"husky": "^9.0.11",
"jest": "29.0.0",
"ts-jest": "^29.0.2",
"ts-proto": "1.121.6",
@ -55,6 +65,8 @@
"test": "jest --runInBand --verbose --testPathPattern=src",
"test:auctions": "TEST_AUCTIONS_ENABLED=1 jest --runInBand --verbose src/auction.test.ts",
"test:nameservice-expiry": "TEST_NAMESERVICE_EXPIRY=1 jest --runInBand --verbose src/nameservice-expiry.test.ts",
"build": "tsc"
"build": "tsc",
"lint": "eslint .",
"prepare": "husky"
}
}

View File

@ -7,17 +7,17 @@ import secp256k1 from 'secp256k1';
import { utils } from 'ethers';
import { sha256 } from 'js-sha256';
import { MessageTypes, signTypedData, SignTypedDataVersion } from '@metamask/eth-sig-util';
import { Ripemd160 } from "@cosmjs/crypto";
import { Ripemd160 } from '@cosmjs/crypto';
import { fromHex, toHex } from '@cosmjs/encoding';
import { ethToEthermint } from "@tharsis/address-converter"
import { ethToEthermint } from '@tharsis/address-converter';
import { encodeSecp256k1Pubkey } from '@cosmjs/amino';
import { DirectSecp256k1Wallet } from "@cosmjs/proto-signing";
import { DirectSecp256k1Wallet } from '@cosmjs/proto-signing';
import { Payload, Signature } from './types';
const AMINO_PREFIX = 'EB5AE98721';
const HDPATH = "m/44'/60'/0'/0";
const ACCOUNT_PREFIX = "laconic";
const ACCOUNT_PREFIX = 'laconic';
const bip32 = BIP32Factory(ecc);
@ -33,27 +33,27 @@ interface TypedMessageDomain {
* Registry account.
*/
export class Account {
_privateKey: Buffer
_publicKey!: Uint8Array
_encodedPubkey!: string
_formattedCosmosAddress!: string
_registryPublicKey!: string
_registryAddress!: string
_ethAddress!: string
_wallet!: DirectSecp256k1Wallet
_address!: string
_privateKey: Buffer;
_publicKey!: Uint8Array;
_encodedPubkey!: string;
_formattedCosmosAddress!: string;
_registryPublicKey!: string;
_registryAddress!: string;
_ethAddress!: string;
_wallet!: DirectSecp256k1Wallet;
_address!: string;
/**
* Generate bip39 mnemonic.
*/
static generateMnemonic() {
static generateMnemonic () {
return bip39.generateMnemonic();
}
/**
* Generate private key from mnemonic.
*/
static async generateFromMnemonic(mnemonic: string) {
static async generateFromMnemonic (mnemonic: string) {
assert(mnemonic);
const seed = await bip39.mnemonicToSeed(mnemonic);
@ -68,36 +68,36 @@ export class Account {
/**
* New Account.
*/
constructor(privateKey: Buffer) {
constructor (privateKey: Buffer) {
assert(privateKey);
this._privateKey = privateKey;
}
get privateKey() {
get privateKey () {
return this._privateKey;
}
get encodedPubkey() {
get encodedPubkey () {
return this._encodedPubkey;
}
get formattedCosmosAddress() {
get formattedCosmosAddress () {
return this._formattedCosmosAddress;
}
get registryPublicKey() {
get registryPublicKey () {
return this._registryPublicKey;
}
get registryAddress() {
get registryAddress () {
return this._registryAddress;
}
get address() {
get address () {
return this._address;
}
get wallet() {
get wallet () {
return this._wallet;
}
@ -107,14 +107,14 @@ export class Account {
ACCOUNT_PREFIX
);
this._address = (await this._wallet.getAccounts())[0].address
this._address = (await this._wallet.getAccounts())[0].address;
// Generate public key.
this._publicKey = secp256k1.publicKeyCreate(this._privateKey)
this._encodedPubkey = encodeSecp256k1Pubkey(this._publicKey).value
this._publicKey = secp256k1.publicKeyCreate(this._privateKey);
this._encodedPubkey = encodeSecp256k1Pubkey(this._publicKey).value;
// 2. Generate eth address.
this._ethAddress = utils.computeAddress(this._publicKey)
this._ethAddress = utils.computeAddress(this._publicKey);
// 3. Generate cosmos-sdk formatted address.
this._formattedCosmosAddress = ethToEthermint(this._ethAddress);
@ -131,21 +131,21 @@ export class Account {
/**
* Get private key.
*/
getPrivateKey() {
getPrivateKey () {
return this._privateKey.toString('hex');
}
/**
* Get cosmos address.
*/
getCosmosAddress() {
getCosmosAddress () {
return this._formattedCosmosAddress;
}
/**
* Get record signature.
*/
async signRecord(record: any) {
async signRecord (record: any) {
assert(record);
const recordAsJson = canonicalStringify(record);
@ -162,14 +162,14 @@ export class Account {
return Buffer.from(sigObj.signature);
}
async signPayload(payload: Payload) {
async signPayload (payload: Payload) {
assert(payload);
const { record } = payload;
const messageToSign = record.getMessageToSign();
const sig = await this.signRecord(messageToSign);
assert(this.registryPublicKey)
assert(this.registryPublicKey);
const signature = new Signature(this.registryPublicKey, sig.toString('base64'));
payload.addSignature(signature);
@ -179,7 +179,7 @@ export class Account {
/**
* Sign message.
*/
sign(message: any) {
sign (message: any) {
assert(message);
const eipMessageDomain: any = message.eipToSign.domain;
@ -192,7 +192,7 @@ export class Account {
},
privateKey: this._privateKey,
version: SignTypedDataVersion.V4
})
});
return signature;
}

View File

@ -119,7 +119,6 @@ if (!process.env.TEST_AUCTIONS_ENABLED) {
TEST_AUCTION_ENABLED=true ./init.sh
Run tests:
yarn test:auctions

View File

@ -2,13 +2,13 @@ import path from 'path';
import { Registry } from './index';
import { ensureUpdatedConfig, getConfig, getLaconic2Config } from './testing/helper';
import { DENOM } from './constants'
import { DENOM } from './constants';
const WATCHER_YML_PATH = path.join(__dirname, './testing/data/watcher.yml');
const BOND_AMOUNT = "10000";
const BOND_AMOUNT = '10000';
const { chainId, restEndpoint, gqlEndpoint, privateKey, fee } = getConfig();
const { fee: laconic2Fee } = getLaconic2Config()
const { fee: laconic2Fee } = getLaconic2Config();
jest.setTimeout(90 * 1000);
@ -32,7 +32,7 @@ const bondTests = () => {
});
describe('With bond created', () => {
let bond1: any
let bond1: any;
beforeAll(async () => {
let bondId1 = await registry.getNextBondId(privateKey);
@ -67,7 +67,7 @@ const bondTests = () => {
});
test('Refill bond.', async () => {
const refillAmount = "500";
const refillAmount = '500';
const total = (parseInt(BOND_AMOUNT) + parseInt(refillAmount)).toString();
await registry.refillBond({ id: bond1.id, denom: DENOM, amount: refillAmount }, privateKey, laconic2Fee);
const [bond] = await registry.getBondsByIds([bond1.id]);
@ -78,7 +78,7 @@ const bondTests = () => {
});
test('Withdraw bond.', async () => {
await registry.withdrawBond({ id: bond1.id, denom: DENOM, amount: "500" }, privateKey, laconic2Fee);
await registry.withdrawBond({ id: bond1.id, denom: DENOM, amount: '500' }, privateKey, laconic2Fee);
const [bond] = await registry.getBondsByIds([bond1.id]);
expect(bond).toBeDefined();
expect(bond.id).toBe(bond1.id);
@ -89,11 +89,10 @@ const bondTests = () => {
test('Cancel bond.', async () => {
await registry.cancelBond({ id: bond1.id }, privateKey, laconic2Fee);
const [bond] = await registry.getBondsByIds([bond1.id]);
expect(bond.id).toBe("");
expect(bond.owner).toBe("");
expect(bond.id).toBe('');
expect(bond.owner).toBe('');
expect(bond.balance).toHaveLength(0);
});
});
test('Associate/Dissociate bond.', async () => {

View File

@ -1 +1 @@
export const DENOM = "photon";
export const DENOM = 'photon';

View File

@ -11,25 +11,24 @@ const registryTests = () => {
beforeAll(async () => {
registry = new Registry(gqlEndpoint, restEndpoint, chainId);
});
test('Get account info.', async() => {
test('Get account info.', async () => {
const account = new Account(Buffer.from(privateKey, 'hex'));
const accounts = await registry.getAccounts([account.formattedCosmosAddress]);
expect(accounts).toHaveLength(1)
expect(accounts).toHaveLength(1);
const [accountObj] = accounts;
expect(accountObj.address).toBe(account.formattedCosmosAddress);
expect(accountObj.pubKey).toBe(account.encodedPubkey);
expect(accountObj.number).toBe('0');
expect(accountObj.sequence).toBeDefined();
expect(accountObj.balance).toHaveLength(1);
const [{ type, quantity }] = accountObj.balance
const [{ type, quantity }] = accountObj.balance;
expect(type).toBe('aphoton');
expect(quantity).toBeDefined();
})
});
test('Get account balance.', async() => {
test('Get account balance.', async () => {
const mnenonic1 = Account.generateMnemonic();
const otherAccount = await Account.generateFromMnemonic(mnenonic1);
await registry.sendCoins({ denom: 'aphoton', amount: '100000000', destinationAddress: otherAccount.formattedCosmosAddress }, privateKey, fee);
@ -37,10 +36,10 @@ const registryTests = () => {
const [accountObj] = await registry.getAccounts([otherAccount.formattedCosmosAddress]);
expect(accountObj).toBeDefined();
expect(accountObj.address).toBe(otherAccount.formattedCosmosAddress);
const [{ type, quantity }] = accountObj.balance
const [{ type, quantity }] = accountObj.balance;
expect(type).toBe('aphoton');
expect(quantity).toBe('100000000');
})
}
});
};
describe('Registry', registryTests);

View File

@ -6,12 +6,12 @@ import {
Fee,
createMessageSend,
MessageSendParams
} from '@tharsis/transactions'
} from '@tharsis/transactions';
import { DeliverTxResponse, GasPrice, StdFee } from '@cosmjs/stargate';
import { RegistryClient } from "./registry-client";
import { Account } from "./account";
import { createTransaction } from "./txbuilder";
import { RegistryClient } from './registry-client';
import { Account } from './account';
import { createTransaction } from './txbuilder';
import { Payload, Record } from './types';
import { Util } from './util';
import {
@ -31,7 +31,7 @@ import {
MessageMsgReAssociateRecords,
MessageMsgRefillBond,
MessageMsgWithdrawBond
} from "./messages/bond";
} from './messages/bond';
import {
createTxMsgDeleteName,
createTxMsgReserveAuthority,
@ -64,7 +64,7 @@ export const parseTxResponse = (result: any, parseResponse?: (data: string) => a
const { txhash: hash, height, ...txResponse } = result;
if (parseResponse) {
txResponse.data = parseResponse(txResponse.data)
txResponse.data = parseResponse(txResponse.data);
}
txResponse.events.forEach((event:any) => {
@ -106,25 +106,24 @@ export const createBid = async (chainId: string, auctionId: string, bidderAddres
export const isKeyValid = (key: string) => key && key.match(/^[0-9a-fA-F]{64}$/);
export class Registry {
_endpoints: {[key: string]: string}
_chainID: string
_chain: Chain
_client: RegistryClient
_endpoints: {[key: string]: string};
_chainID: string;
_chain: Chain;
_client: RegistryClient;
static processWriteError(error: string) {
static processWriteError (error: string) {
// error string a stacktrace containing the message.
// https://gist.github.com/nikugogoi/de55d390574ded3466abad8bffd81952#file-txresponse-js-L7
const errorMessage = NAMESERVICE_ERRORS.find(message => error.includes(message))
const errorMessage = NAMESERVICE_ERRORS.find(message => error.includes(message));
if (!errorMessage) {
console.error(error)
console.error(error);
}
return errorMessage || DEFAULT_WRITE_ERROR;
}
constructor(gqlUrl: string, restUrl: string = "", chainId: string = DEFAULT_CHAIN_ID) {
constructor (gqlUrl: string, restUrl = '', chainId: string = DEFAULT_CHAIN_ID) {
this._endpoints = {
rest: restUrl,
gql: gqlUrl
@ -142,43 +141,43 @@ export class Registry {
/**
* Get accounts by addresses.
*/
async getAccounts(addresses: string[]) {
async getAccounts (addresses: string[]) {
return this._client.getAccounts(addresses);
}
get endpoints() {
get endpoints () {
return this._endpoints;
}
get chainID() {
get chainID () {
return this._chainID;
}
/**
* Get server status.
*/
async getStatus() {
async getStatus () {
return this._client.getStatus();
}
/**
* Get records by ids.
*/
async getRecordsByIds(ids: string[], refs = false) {
async getRecordsByIds (ids: string[], refs = false) {
return this._client.getRecordsByIds(ids, refs);
}
/**
* Get records by attributes.
*/
async queryRecords(attributes: {[key: string]: any}, all = false, refs = false) {
async queryRecords (attributes: {[key: string]: any}, all = false, refs = false) {
return this._client.queryRecords(attributes, all, refs);
}
/**
* Resolve names to records.
*/
async resolveNames(names: string[], refs = false) {
async resolveNames (names: string[], refs = false) {
return this._client.resolveNames(names, refs);
}
@ -186,7 +185,7 @@ export class Registry {
* Publish record.
* @param transactionPrivateKey - private key in HEX to sign transaction.
*/
async setRecord(
async setRecord (
params: { privateKey: string, record: any, bondId: string },
transactionPrivateKey: string,
fee: Fee
@ -200,12 +199,12 @@ export class Registry {
/**
* Send coins.
*/
async sendCoins(params: MessageSendParams, privateKey: string, fee: Fee) {
async sendCoins (params: MessageSendParams, privateKey: string, fee: Fee) {
let result;
const account = new Account(Buffer.from(privateKey, 'hex'));
const sender = await this._getSender(account);
const msg = createMessageSend(this._chain, sender, fee, '', params)
const msg = createMessageSend(this._chain, sender, fee, '', params);
result = await this._submitTx(msg, privateKey, sender);
return parseTxResponse(result);
@ -214,10 +213,10 @@ export class Registry {
/**
* Computes the next bondId for the given account private key.
*/
async getNextBondId(privateKey: string) {
async getNextBondId (privateKey: string) {
let result;
const account = new Account(Buffer.from(privateKey, 'hex'));
await account.init()
await account.init();
const accounts = await this.getAccounts([account.address]);
if (!accounts.length) {
throw new Error('Account does not exist.');
@ -233,24 +232,24 @@ export class Registry {
/**
* Get bonds by ids.
*/
async getBondsByIds(ids: string[]) {
async getBondsByIds (ids: string[]) {
return this._client.getBondsByIds(ids);
}
/**
* Query bonds by attributes.
*/
async queryBonds(attributes = {}) {
async queryBonds (attributes = {}) {
return this._client.queryBonds(attributes);
}
/**
* Create bond.
*/
async createBond({ denom , amount }: MessageMsgCreateBond, privateKey: string, fee: StdFee): Promise<MsgCreateBondResponse> {
const account = new Account(Buffer.from(privateKey, 'hex'))
await account.init()
const laconicClient = await this.getLaconicClient(account)
async createBond ({ denom, amount }: MessageMsgCreateBond, privateKey: string, fee: StdFee): Promise<MsgCreateBondResponse> {
const account = new Account(Buffer.from(privateKey, 'hex'));
await account.init();
const laconicClient = await this.getLaconicClient(account);
const response: DeliverTxResponse = await laconicClient.createBond(
account.address,
@ -259,16 +258,16 @@ export class Registry {
fee
);
return laconicClient.registry.decode(response.msgResponses[0])
return laconicClient.registry.decode(response.msgResponses[0]);
}
/**
* Refill bond.
*/
async refillBond({ denom, amount, id}: MessageMsgRefillBond, privateKey: string, fee: StdFee): Promise<MsgRefillBondResponse> {
const account = new Account(Buffer.from(privateKey, 'hex'))
await account.init()
const laconicClient = await this.getLaconicClient(account)
async refillBond ({ denom, amount, id }: MessageMsgRefillBond, privateKey: string, fee: StdFee): Promise<MsgRefillBondResponse> {
const account = new Account(Buffer.from(privateKey, 'hex'));
await account.init();
const laconicClient = await this.getLaconicClient(account);
const response: DeliverTxResponse = await laconicClient.refillBond(
account.address,
@ -278,16 +277,16 @@ export class Registry {
fee
);
return laconicClient.registry.decode(response.msgResponses[0])
return laconicClient.registry.decode(response.msgResponses[0]);
}
/**
* Withdraw (from) bond.
*/
async withdrawBond({ denom, amount, id }: MessageMsgWithdrawBond, privateKey: string, fee: StdFee): Promise<MsgWithdrawBondResponse> {
const account = new Account(Buffer.from(privateKey, 'hex'))
await account.init()
const laconicClient = await this.getLaconicClient(account)
async withdrawBond ({ denom, amount, id }: MessageMsgWithdrawBond, privateKey: string, fee: StdFee): Promise<MsgWithdrawBondResponse> {
const account = new Account(Buffer.from(privateKey, 'hex'));
await account.init();
const laconicClient = await this.getLaconicClient(account);
const response: DeliverTxResponse = await laconicClient.withdrawBond(
account.address,
@ -297,16 +296,16 @@ export class Registry {
fee
);
return laconicClient.registry.decode(response.msgResponses[0])
return laconicClient.registry.decode(response.msgResponses[0]);
}
/**
* Cancel bond.
*/
async cancelBond({ id }: MessageMsgCancelBond, privateKey: string, fee: StdFee): Promise<MsgCancelBondResponse> {
const account = new Account(Buffer.from(privateKey, 'hex'))
await account.init()
const laconicClient = await this.getLaconicClient(account)
async cancelBond ({ id }: MessageMsgCancelBond, privateKey: string, fee: StdFee): Promise<MsgCancelBondResponse> {
const account = new Account(Buffer.from(privateKey, 'hex'));
await account.init();
const laconicClient = await this.getLaconicClient(account);
const response: DeliverTxResponse = await laconicClient.cancelBond(
account.address,
@ -314,18 +313,18 @@ export class Registry {
fee
);
return laconicClient.registry.decode(response.msgResponses[0])
return laconicClient.registry.decode(response.msgResponses[0]);
}
/**
* Associate record with bond.
*/
async associateBond(params: MessageMsgAssociateBond, privateKey: string, fee: Fee) {
async associateBond (params: MessageMsgAssociateBond, privateKey: string, fee: Fee) {
let result;
const account = new Account(Buffer.from(privateKey, 'hex'));
const sender = await this._getSender(account);
const msg = createTxMsgAssociateBond(this._chain, sender, fee, '', params)
const msg = createTxMsgAssociateBond(this._chain, sender, fee, '', params);
result = await this._submitTx(msg, privateKey, sender);
return parseTxResponse(result);
@ -334,12 +333,12 @@ export class Registry {
/**
* Dissociate record from bond.
*/
async dissociateBond(params: MessageMsgDissociateBond, privateKey: string, fee: Fee) {
async dissociateBond (params: MessageMsgDissociateBond, privateKey: string, fee: Fee) {
let result;
const account = new Account(Buffer.from(privateKey, 'hex'));
const sender = await this._getSender(account);
const msg = createTxMsgDissociateBond(this._chain, sender, fee, '', params)
const msg = createTxMsgDissociateBond(this._chain, sender, fee, '', params);
result = await this._submitTx(msg, privateKey, sender);
return parseTxResponse(result);
@ -348,12 +347,12 @@ export class Registry {
/**
* Dissociate all records from bond.
*/
async dissociateRecords(params: MessageMsgDissociateRecords, privateKey: string, fee: Fee) {
async dissociateRecords (params: MessageMsgDissociateRecords, privateKey: string, fee: Fee) {
let result;
const account = new Account(Buffer.from(privateKey, 'hex'));
const sender = await this._getSender(account);
const msg = createTxMsgDissociateRecords(this._chain, sender, fee, '', params)
const msg = createTxMsgDissociateRecords(this._chain, sender, fee, '', params);
result = await this._submitTx(msg, privateKey, sender);
return parseTxResponse(result);
@ -362,12 +361,12 @@ export class Registry {
/**
* Reassociate records (switch bond).
*/
async reassociateRecords(params: MessageMsgReAssociateRecords, privateKey: string, fee: Fee) {
async reassociateRecords (params: MessageMsgReAssociateRecords, privateKey: string, fee: Fee) {
let result;
const account = new Account(Buffer.from(privateKey, 'hex'));
const sender = await this._getSender(account);
const msg = createTxMsgReAssociateRecords(this._chain, sender, fee, '', params)
const msg = createTxMsgReAssociateRecords(this._chain, sender, fee, '', params);
result = await this._submitTx(msg, privateKey, sender);
return parseTxResponse(result);
@ -376,7 +375,7 @@ export class Registry {
/**
* Reserve authority.
*/
async reserveAuthority(params: { name: string, owner?: string }, privateKey: string, fee: Fee) {
async reserveAuthority (params: { name: string, owner?: string }, privateKey: string, fee: Fee) {
let result;
const account = new Account(Buffer.from(privateKey, 'hex'));
const sender = await this._getSender(account);
@ -384,9 +383,9 @@ export class Registry {
const msgParams = {
name: params.name,
owner: params.owner || sender.accountAddress
}
};
const msg = createTxMsgReserveAuthority(this._chain, sender, fee, '', msgParams)
const msg = createTxMsgReserveAuthority(this._chain, sender, fee, '', msgParams);
result = await this._submitTx(msg, privateKey, sender);
return parseTxResponse(result);
@ -395,12 +394,12 @@ export class Registry {
/**
* Set authority bond.
*/
async setAuthorityBond(params: MessageMsgSetAuthorityBond, privateKey: string, fee: Fee) {
async setAuthorityBond (params: MessageMsgSetAuthorityBond, privateKey: string, fee: Fee) {
let result;
const account = new Account(Buffer.from(privateKey, 'hex'));
const sender = await this._getSender(account);
const msg = createTxMsgSetAuthorityBond(this._chain, sender, fee, '', params)
const msg = createTxMsgSetAuthorityBond(this._chain, sender, fee, '', params);
result = await this._submitTx(msg, privateKey, sender);
return parseTxResponse(result);
@ -409,12 +408,12 @@ export class Registry {
/**
* Commit auction bid.
*/
async commitBid(params: MessageMsgCommitBid, privateKey: string, fee: Fee) {
async commitBid (params: MessageMsgCommitBid, privateKey: string, fee: Fee) {
let result;
const account = new Account(Buffer.from(privateKey, 'hex'));
const sender = await this._getSender(account);
const msg = createTxMsgCommitBid(this._chain, sender, fee, '', params)
const msg = createTxMsgCommitBid(this._chain, sender, fee, '', params);
result = await this._submitTx(msg, privateKey, sender);
return parseTxResponse(result);
@ -423,12 +422,12 @@ export class Registry {
/**
* Reveal auction bid.
*/
async revealBid(params: MessageMsgRevealBid, privateKey: string, fee: Fee) {
async revealBid (params: MessageMsgRevealBid, privateKey: string, fee: Fee) {
let result;
const account = new Account(Buffer.from(privateKey, 'hex'));
const sender = await this._getSender(account);
const msg = createTxMsgRevealBid(this._chain, sender, fee, '', params)
const msg = createTxMsgRevealBid(this._chain, sender, fee, '', params);
result = await this._submitTx(msg, privateKey, sender);
return parseTxResponse(result);
@ -437,26 +436,26 @@ export class Registry {
/**
* Get records by ids.
*/
async getAuctionsByIds(ids: string[]) {
async getAuctionsByIds (ids: string[]) {
return this._client.getAuctionsByIds(ids);
}
/**
* Lookup authorities by names.
*/
async lookupAuthorities(names: string[], auction = false) {
async lookupAuthorities (names: string[], auction = false) {
return this._client.lookupAuthorities(names, auction);
}
/**
* Set name (CRN) to record ID (CID).
*/
async setName(params: MessageMsgSetName, privateKey: string, fee: Fee) {
async setName (params: MessageMsgSetName, privateKey: string, fee: Fee) {
let result;
const account = new Account(Buffer.from(privateKey, 'hex'));
const sender = await this._getSender(account);
const msg = createTxMsgSetName(this._chain, sender, fee, '', params)
const msg = createTxMsgSetName(this._chain, sender, fee, '', params);
result = await this._submitTx(msg, privateKey, sender);
return parseTxResponse(result);
@ -465,19 +464,19 @@ export class Registry {
/**
* Lookup naming information.
*/
async lookupNames(names: string[], history = false) {
async lookupNames (names: string[], history = false) {
return this._client.lookupNames(names, history);
}
/**
* Delete name (CRN) mapping.
*/
async deleteName(params: MessageMsgDeleteName, privateKey: string, fee: Fee) {
async deleteName (params: MessageMsgDeleteName, privateKey: string, fee: Fee) {
let result;
const account = new Account(Buffer.from(privateKey, 'hex'));
const sender = await this._getSender(account);
const msg = createTxMsgDeleteName(this._chain, sender, fee, '', params)
const msg = createTxMsgDeleteName(this._chain, sender, fee, '', params);
result = await this._submitTx(msg, privateKey, sender);
return parseTxResponse(result);
@ -488,7 +487,7 @@ export class Registry {
* @param privateKey - private key in HEX to sign message.
* @param txPrivateKey - private key in HEX to sign transaction.
*/
async _submitRecordTx(
async _submitRecordTx (
{ privateKey, record, bondId }: { privateKey: string, record: any, bondId: string },
txPrivateKey: string,
fee: Fee
@ -512,7 +511,7 @@ export class Registry {
return this._submitRecordPayloadTx({ payload, bondId }, txPrivateKey, fee);
}
async _submitRecordPayloadTx(params: MessageMsgSetRecord, privateKey: string, fee: Fee) {
async _submitRecordPayloadTx (params: MessageMsgSetRecord, privateKey: string, fee: Fee) {
if (!isKeyValid(privateKey)) {
throw new Error('Registry privateKey should be a hex string.');
}
@ -524,14 +523,14 @@ export class Registry {
const account = new Account(Buffer.from(privateKey, 'hex'));
const sender = await this._getSender(account);
const msg = createTxMsgSetRecord(this._chain, sender, fee, '', params)
const msg = createTxMsgSetRecord(this._chain, sender, fee, '', params);
return this._submitTx(msg, privateKey, sender);
}
/**
* Submit a generic Tx to the chain.
*/
async _submitTx(message: any, privateKey: string, sender: Sender) {
async _submitTx (message: any, privateKey: string, sender: Sender) {
// Check private key.
if (!isKeyValid(privateKey)) {
throw new Error('Registry privateKey should be a hex string.');
@ -543,7 +542,7 @@ export class Registry {
// Generate signed Tx.
const transaction = createTransaction(message, account, sender, this._chain);
const tx = generatePostBodyBroadcast(transaction, BroadcastMode.Block)
const tx = generatePostBodyBroadcast(transaction, BroadcastMode.Block);
// Submit Tx to chain.
const { tx_response: response } = await this._client.submit(tx);
@ -551,7 +550,7 @@ export class Registry {
if (response.code !== 0) {
// Throw error when transaction is not successful.
// https://docs.starport.com/guide/nameservice/05-play.html#buy-name-transaction-details
throw new Error(Registry.processWriteError(response.raw_log))
throw new Error(Registry.processWriteError(response.raw_log));
}
return response;
@ -561,10 +560,10 @@ export class Registry {
* https://evmos.dev/basics/chain_id.html
*/
_parseEthChainId (chainId: string) {
const [ idWithChainNumber ] = chainId.split('-')
const [ _, ethChainId ] = idWithChainNumber.split('_')
const [idWithChainNumber] = chainId.split('-');
const [_, ethChainId] = idWithChainNumber.split('_');
return Number(ethChainId)
return Number(ethChainId);
}
/**
@ -582,13 +581,13 @@ export class Registry {
accountAddress: account.formattedCosmosAddress,
sequence: sequence,
accountNumber: number,
pubkey: account.encodedPubkey,
}
pubkey: account.encodedPubkey
};
}
async getLaconicClient(account: Account){
return LaconicClient.connectWithSigner(this._endpoints.rest, account.wallet)
async getLaconicClient (account: Account) {
return LaconicClient.connectWithSigner(this._endpoints.rest, account.wallet);
}
}
export { Account }
export { Account };

View File

@ -1,55 +1,45 @@
import { GeneratedType, OfflineSigner, Registry } from "@cosmjs/proto-signing";
import { GeneratedType, OfflineSigner, Registry } from '@cosmjs/proto-signing';
import {
defaultRegistryTypes,
DeliverTxResponse,
SigningStargateClient,
SigningStargateClientOptions,
StdFee,
} from "@cosmjs/stargate"
import { Comet38Client } from "@cosmjs/tendermint-rpc"
import { MsgCancelBondEncodeObject, MsgCreateBondEncodeObject, MsgRefillBondEncodeObject, MsgWithdrawBondEncodeObject, bondTypes, typeUrlMsgCancelBond, typeUrlMsgCreateBond, typeUrlMsgRefillBond, typeUrlMsgWithdrawBond } from "./types/cerc/bond/message";
import { Coin } from "./proto2/cosmos/base/v1beta1/coin";
StdFee
} from '@cosmjs/stargate';
import { Comet38Client } from '@cosmjs/tendermint-rpc';
import { MsgCancelBondEncodeObject, MsgCreateBondEncodeObject, MsgRefillBondEncodeObject, MsgWithdrawBondEncodeObject, bondTypes, typeUrlMsgCancelBond, typeUrlMsgCreateBond, typeUrlMsgRefillBond, typeUrlMsgWithdrawBond } from './types/cerc/bond/message';
import { Coin } from './proto2/cosmos/base/v1beta1/coin';
export const laconicDefaultRegistryTypes: ReadonlyArray<[string, GeneratedType]> = [
...defaultRegistryTypes,
...bondTypes,
]
...bondTypes
];
function createDefaultRegistry(): Registry {
function createDefaultRegistry (): Registry {
return new Registry(laconicDefaultRegistryTypes);
}
export class LaconicClient extends SigningStargateClient {
public static async connectWithSigner(
public static async connectWithSigner (
endpoint: string,
signer: OfflineSigner,
options: SigningStargateClientOptions = {},
options: SigningStargateClientOptions = {}
): Promise<LaconicClient> {
const cometClient = await Comet38Client.connect(endpoint);
return new LaconicClient(cometClient, signer, {
registry: createDefaultRegistry(),
...options,
...options
});
}
protected constructor(
cometClient: Comet38Client,
signer: OfflineSigner,
options: SigningStargateClientOptions,
) {
super(cometClient, signer, options);
}
public async createBond(
public async createBond (
signer: string,
denom: string,
amount: string,
fee: StdFee | "auto" | number,
memo = "",
fee: StdFee | 'auto' | number,
memo = ''
): Promise<DeliverTxResponse> {
const createMsg: MsgCreateBondEncodeObject = {
typeUrl: typeUrlMsgCreateBond,
@ -61,19 +51,19 @@ export class LaconicClient extends SigningStargateClient {
amount
})
]
},
}
};
return this.signAndBroadcast(signer, [createMsg], fee, memo);
}
public async refillBond(
public async refillBond (
signer: string,
denom: string,
amount: string,
id: string,
fee: StdFee | "auto" | number,
memo = "",
fee: StdFee | 'auto' | number,
memo = ''
): Promise<DeliverTxResponse> {
const createMsg: MsgRefillBondEncodeObject = {
typeUrl: typeUrlMsgRefillBond,
@ -86,19 +76,19 @@ export class LaconicClient extends SigningStargateClient {
amount
})
]
},
}
};
return this.signAndBroadcast(signer, [createMsg], fee, memo);
}
public async withdrawBond(
public async withdrawBond (
signer: string,
denom: string,
amount: string,
id: string,
fee: StdFee | "auto" | number,
memo = "",
fee: StdFee | 'auto' | number,
memo = ''
): Promise<DeliverTxResponse> {
const createMsg: MsgWithdrawBondEncodeObject = {
typeUrl: typeUrlMsgWithdrawBond,
@ -111,24 +101,24 @@ export class LaconicClient extends SigningStargateClient {
amount
})
]
},
}
};
return this.signAndBroadcast(signer, [createMsg], fee, memo);
}
public async cancelBond(
public async cancelBond (
signer: string,
id: string,
fee: StdFee | "auto" | number,
memo = "",
fee: StdFee | 'auto' | number,
memo = ''
): Promise<DeliverTxResponse> {
const createMsg: MsgCancelBondEncodeObject = {
typeUrl: typeUrlMsgCancelBond,
value: {
id,
signer
},
}
};
return this.signAndBroadcast(signer, [createMsg], fee, memo);

View File

@ -1,22 +1,22 @@
import {
generateTypes,
} from '@tharsis/eip712'
generateTypes
} from '@tharsis/eip712';
import {
Chain,
Sender,
Fee,
} from '@tharsis/transactions'
Fee
} from '@tharsis/transactions';
import * as auctionTx from '../proto/vulcanize/auction/v1beta1/tx'
import { createTx } from './util'
import * as auctionTx from '../proto/vulcanize/auction/v1beta1/tx';
import { createTx } from './util';
const MSG_COMMIT_BID_TYPES = {
MsgValue: [
{ name: 'auction_id', type: 'string' },
{ name: 'commit_hash', type: 'string' },
{ name: 'signer', type: 'string' },
{ name: 'signer', type: 'string' }
]
}
};
export interface MessageMsgCommitBid {
auctionId: string,
@ -27,64 +27,64 @@ const MSG_REVEAL_BID_TYPES = {
MsgValue: [
{ name: 'auction_id', type: 'string' },
{ name: 'reveal', type: 'string' },
{ name: 'signer', type: 'string' },
{ name: 'signer', type: 'string' }
]
}
};
export interface MessageMsgRevealBid {
auctionId: string,
reveal: string,
}
export function createTxMsgCommitBid(
export function createTxMsgCommitBid (
chain: Chain,
sender: Sender,
fee: Fee,
memo: string,
params: MessageMsgCommitBid,
params: MessageMsgCommitBid
) {
const types = generateTypes(MSG_COMMIT_BID_TYPES)
const types = generateTypes(MSG_COMMIT_BID_TYPES);
const msg = createMsgCommitBid(
params.auctionId,
params.commitHash,
sender.accountAddress,
)
sender.accountAddress
);
const msgCosmos = protoCreateMsgCommitBid(
params.auctionId,
params.commitHash,
sender.accountAddress,
)
sender.accountAddress
);
return createTx(chain, sender, fee, memo, types, msg, msgCosmos)
return createTx(chain, sender, fee, memo, types, msg, msgCosmos);
}
export function createTxMsgRevealBid(
export function createTxMsgRevealBid (
chain: Chain,
sender: Sender,
fee: Fee,
memo: string,
params: MessageMsgRevealBid,
params: MessageMsgRevealBid
) {
const types = generateTypes(MSG_REVEAL_BID_TYPES)
const types = generateTypes(MSG_REVEAL_BID_TYPES);
const msg = createMsgRevealBid(
params.auctionId,
params.reveal,
sender.accountAddress,
)
sender.accountAddress
);
const msgCosmos = protoCreateMsgRevealBid(
params.auctionId,
params.reveal,
sender.accountAddress,
)
sender.accountAddress
);
return createTx(chain, sender, fee, memo, types, msg, msgCosmos)
return createTx(chain, sender, fee, memo, types, msg, msgCosmos);
}
function createMsgCommitBid(
function createMsgCommitBid (
auctionId: string,
commitHash: string,
signer: string
@ -94,9 +94,9 @@ function createMsgCommitBid(
value: {
auction_id: auctionId,
commit_hash: commitHash,
signer,
},
}
signer
}
};
}
const protoCreateMsgCommitBid = (
@ -107,16 +107,16 @@ const protoCreateMsgCommitBid = (
const commitBidMessage = new auctionTx.vulcanize.auction.v1beta1.MsgCommitBid({
auction_id: auctionId,
commit_hash: commitHash,
signer,
})
signer
});
return {
message: commitBidMessage,
path: 'vulcanize.auction.v1beta1.MsgCommitBid',
}
}
path: 'vulcanize.auction.v1beta1.MsgCommitBid'
};
};
function createMsgRevealBid(
function createMsgRevealBid (
auctionId: string,
reveal: string,
signer: string
@ -126,9 +126,9 @@ function createMsgRevealBid(
value: {
auction_id: auctionId,
reveal,
signer,
},
}
signer
}
};
}
const protoCreateMsgRevealBid = (
@ -139,11 +139,11 @@ const protoCreateMsgRevealBid = (
const revealBidMessage = new auctionTx.vulcanize.auction.v1beta1.MsgRevealBid({
auction_id: auctionId,
reveal,
signer,
})
signer
});
return {
message: revealBidMessage,
path: 'vulcanize.auction.v1beta1.MsgRevealBid',
}
}
path: 'vulcanize.auction.v1beta1.MsgRevealBid'
};
};

View File

@ -1,88 +1,88 @@
import {
generateTypes,
} from '@tharsis/eip712'
generateTypes
} from '@tharsis/eip712';
import {
Chain,
Sender,
Fee,
} from '@tharsis/transactions'
Fee
} from '@tharsis/transactions';
import * as bondTx from '../proto/vulcanize/bond/v1beta1/tx'
import * as registryTx from '../proto/vulcanize/registry/v1beta1/tx'
import * as coin from '../proto/cosmos/base/v1beta1/coin'
import { createTx } from './util'
import * as bondTx from '../proto/vulcanize/bond/v1beta1/tx';
import * as registryTx from '../proto/vulcanize/registry/v1beta1/tx';
import * as coin from '../proto/cosmos/base/v1beta1/coin';
import { createTx } from './util';
const MSG_CREATE_BOND_TYPES = {
MsgValue: [
{ name: 'signer', type: 'string' },
{ name: 'coins', type: 'TypeCoins[]' },
{ name: 'coins', type: 'TypeCoins[]' }
],
TypeCoins: [
{ name: 'denom', type: 'string' },
{ name: 'amount', type: 'string' },
],
}
{ name: 'amount', type: 'string' }
]
};
const MSG_REFILL_BOND_TYPES = {
MsgValue: [
{ name: 'id', type: 'string' },
{ name: 'signer', type: 'string' },
{ name: 'coins', type: 'TypeCoins[]' },
{ name: 'coins', type: 'TypeCoins[]' }
],
TypeCoins: [
{ name: 'denom', type: 'string' },
{ name: 'amount', type: 'string' },
],
}
{ name: 'amount', type: 'string' }
]
};
const MSG_WITHDRAW_BOND_TYPES = {
MsgValue: [
{ name: 'id', type: 'string' },
{ name: 'signer', type: 'string' },
{ name: 'coins', type: 'TypeCoins[]' },
{ name: 'coins', type: 'TypeCoins[]' }
],
TypeCoins: [
{ name: 'denom', type: 'string' },
{ name: 'amount', type: 'string' },
],
}
{ name: 'amount', type: 'string' }
]
};
const MSG_CANCEL_BOND_TYPES = {
MsgValue: [
{ name: 'id', type: 'string' },
{ name: 'signer', type: 'string' },
{ name: 'signer', type: 'string' }
]
}
};
const MSG_ASSOCIATE_BOND_TYPES = {
MsgValue: [
{ name: 'record_id', type: 'string' },
{ name: 'bond_id', type: 'string' },
{ name: 'signer', type: 'string' },
{ name: 'signer', type: 'string' }
]
}
};
const MSG_DISSOCIATE_BOND_TYPES = {
MsgValue: [
{ name: 'record_id', type: 'string' },
{ name: 'signer', type: 'string' },
{ name: 'signer', type: 'string' }
]
}
};
const MSG_DISSOCIATE_RECORDS_TYPES = {
MsgValue: [
{ name: 'bond_id', type: 'string' },
{ name: 'signer', type: 'string' },
{ name: 'signer', type: 'string' }
]
}
};
const MSG_REASSOCIATE_RECORDS_TYPES = {
MsgValue: [
{ name: 'new_bond_id', type: 'string' },
{ name: 'old_bond_id', type: 'string' },
{ name: 'signer', type: 'string' },
{ name: 'signer', type: 'string' }
]
}
};
export interface MessageMsgCreateBond {
amount: string
@ -123,200 +123,200 @@ export interface MessageMsgReAssociateRecords {
oldBondId: string
}
export function createTxMsgCreateBond(
export function createTxMsgCreateBond (
chain: Chain,
sender: Sender,
fee: Fee,
memo: string,
params: MessageMsgCreateBond,
params: MessageMsgCreateBond
) {
const types = generateTypes(MSG_CREATE_BOND_TYPES)
const types = generateTypes(MSG_CREATE_BOND_TYPES);
const msg = createMsgCreateBond(
sender.accountAddress,
params.amount,
params.denom
)
);
const msgCosmos = protoCreateMsgCreateBond(
sender.accountAddress,
params.amount,
params.denom
)
);
return createTx(chain, sender, fee, memo, types, msg, msgCosmos)
return createTx(chain, sender, fee, memo, types, msg, msgCosmos);
}
export function createTxMsgRefillBond(
export function createTxMsgRefillBond (
chain: Chain,
sender: Sender,
fee: Fee,
memo: string,
params: MessageMsgRefillBond,
params: MessageMsgRefillBond
) {
const types = generateTypes(MSG_REFILL_BOND_TYPES)
const types = generateTypes(MSG_REFILL_BOND_TYPES);
const msg = createMsgRefillBond(
params.id,
sender.accountAddress,
params.amount,
params.denom
)
);
const msgCosmos = protoCreateMsgRefillBond(
params.id,
sender.accountAddress,
params.amount,
params.denom
)
);
return createTx(chain, sender, fee, memo, types, msg, msgCosmos)
return createTx(chain, sender, fee, memo, types, msg, msgCosmos);
}
export function createTxMsgWithdrawBond(
export function createTxMsgWithdrawBond (
chain: Chain,
sender: Sender,
fee: Fee,
memo: string,
params: MessageMsgWithdrawBond,
params: MessageMsgWithdrawBond
) {
const types = generateTypes(MSG_WITHDRAW_BOND_TYPES)
const types = generateTypes(MSG_WITHDRAW_BOND_TYPES);
const msg = createMsgWithdrawBond(
params.id,
sender.accountAddress,
params.amount,
params.denom
)
);
const msgCosmos = protoCreateMsgWithdrawBond(
params.id,
sender.accountAddress,
params.amount,
params.denom
)
);
return createTx(chain, sender, fee, memo, types, msg, msgCosmos)
return createTx(chain, sender, fee, memo, types, msg, msgCosmos);
}
export function createTxMsgCancelBond(
export function createTxMsgCancelBond (
chain: Chain,
sender: Sender,
fee: Fee,
memo: string,
params: MessageMsgCancelBond,
params: MessageMsgCancelBond
) {
const types = generateTypes(MSG_CANCEL_BOND_TYPES)
const types = generateTypes(MSG_CANCEL_BOND_TYPES);
const msg = createMsgCancelBond(
params.id,
sender.accountAddress
)
);
const msgCosmos = protoCreateMsgCancelBond(
params.id,
sender.accountAddress
)
);
return createTx(chain, sender, fee, memo, types, msg, msgCosmos)
return createTx(chain, sender, fee, memo, types, msg, msgCosmos);
}
export function createTxMsgAssociateBond(
export function createTxMsgAssociateBond (
chain: Chain,
sender: Sender,
fee: Fee,
memo: string,
params: MessageMsgAssociateBond,
params: MessageMsgAssociateBond
) {
const types = generateTypes(MSG_ASSOCIATE_BOND_TYPES)
const types = generateTypes(MSG_ASSOCIATE_BOND_TYPES);
const msg = createMsgAssociateBond(
params.recordId,
params.bondId,
sender.accountAddress
)
);
const msgCosmos = protoCreateMsgAssociateBond(
params.recordId,
params.bondId,
sender.accountAddress
)
);
return createTx(chain, sender, fee, memo, types, msg, msgCosmos)
return createTx(chain, sender, fee, memo, types, msg, msgCosmos);
}
export function createTxMsgDissociateBond(
export function createTxMsgDissociateBond (
chain: Chain,
sender: Sender,
fee: Fee,
memo: string,
params: MessageMsgDissociateBond,
params: MessageMsgDissociateBond
) {
const types = generateTypes(MSG_DISSOCIATE_BOND_TYPES)
const types = generateTypes(MSG_DISSOCIATE_BOND_TYPES);
const msg = createMsgDissociateBond(
params.recordId,
sender.accountAddress
)
);
const msgCosmos = protoCreateMsgDissociateBond(
params.recordId,
sender.accountAddress
)
);
return createTx(chain, sender, fee, memo, types, msg, msgCosmos)
return createTx(chain, sender, fee, memo, types, msg, msgCosmos);
}
export function createTxMsgDissociateRecords(
export function createTxMsgDissociateRecords (
chain: Chain,
sender: Sender,
fee: Fee,
memo: string,
params: MessageMsgDissociateRecords,
params: MessageMsgDissociateRecords
) {
const types = generateTypes(MSG_DISSOCIATE_RECORDS_TYPES)
const types = generateTypes(MSG_DISSOCIATE_RECORDS_TYPES);
const msg = createMsgDissociateRecords(
params.bondId,
sender.accountAddress
)
);
const msgCosmos = protoCreateMsgDissociateRecords(
params.bondId,
sender.accountAddress
)
);
return createTx(chain, sender, fee, memo, types, msg, msgCosmos)
return createTx(chain, sender, fee, memo, types, msg, msgCosmos);
}
export function createTxMsgReAssociateRecords(
export function createTxMsgReAssociateRecords (
chain: Chain,
sender: Sender,
fee: Fee,
memo: string,
params: MessageMsgReAssociateRecords,
params: MessageMsgReAssociateRecords
) {
const types = generateTypes(MSG_REASSOCIATE_RECORDS_TYPES)
const types = generateTypes(MSG_REASSOCIATE_RECORDS_TYPES);
const msg = createMsgReAssociateRecords(
params.newBondId,
params.oldBondId,
sender.accountAddress
)
);
const msgCosmos = protoCreateMsgReAssociateRecords(
params.newBondId,
params.oldBondId,
sender.accountAddress
)
);
return createTx(chain, sender, fee, memo, types, msg, msgCosmos)
return createTx(chain, sender, fee, memo, types, msg, msgCosmos);
}
function createMsgCreateBond(
function createMsgCreateBond (
signer: string,
amount: string,
denom: string,
denom: string
) {
return {
type: 'bond/MsgCreateBond',
@ -324,40 +324,40 @@ function createMsgCreateBond(
coins: [
{
amount,
denom,
},
denom
}
],
signer
},
}
}
};
}
const protoCreateMsgCreateBond = (
signer: string,
amount: string,
denom: string,
denom: string
) => {
const value = new coin.cosmos.base.v1beta1.Coin({
denom,
amount,
})
amount
});
const createBondMessage = new bondTx.vulcanize.bond.v1beta1.MsgCreateBond({
signer,
coins: [value]
})
});
return {
message: createBondMessage,
path: 'vulcanize.bond.v1beta1.MsgCreateBond',
}
}
path: 'vulcanize.bond.v1beta1.MsgCreateBond'
};
};
function createMsgRefillBond(
function createMsgRefillBond (
id: string,
signer: string,
amount: string,
denom: string,
denom: string
) {
return {
type: 'bond/MsgRefillBond',
@ -365,43 +365,43 @@ function createMsgRefillBond(
coins: [
{
amount,
denom,
},
denom
}
],
id,
signer
},
}
}
};
}
const protoCreateMsgRefillBond = (
id: string,
signer: string,
amount: string,
denom: string,
denom: string
) => {
const value = new coin.cosmos.base.v1beta1.Coin({
denom,
amount,
})
amount
});
const refillBondMessage = new bondTx.vulcanize.bond.v1beta1.MsgRefillBond({
id,
signer,
coins: [value]
})
});
return {
message: refillBondMessage,
path: 'vulcanize.bond.v1beta1.MsgRefillBond',
}
}
path: 'vulcanize.bond.v1beta1.MsgRefillBond'
};
};
function createMsgWithdrawBond(
function createMsgWithdrawBond (
id: string,
signer: string,
amount: string,
denom: string,
denom: string
) {
return {
type: 'bond/MsgWithdrawBond',
@ -410,38 +410,38 @@ function createMsgWithdrawBond(
coins: [
{
amount,
denom,
},
denom
}
],
signer
},
}
}
};
}
const protoCreateMsgWithdrawBond = (
id: string,
signer: string,
amount: string,
denom: string,
denom: string
) => {
const value = new coin.cosmos.base.v1beta1.Coin({
denom,
amount,
})
amount
});
const withdrawBondMessage = new bondTx.vulcanize.bond.v1beta1.MsgWithdrawBond({
id,
signer,
coins: [value]
})
});
return {
message: withdrawBondMessage,
path: 'vulcanize.bond.v1beta1.MsgWithdrawBond',
}
}
path: 'vulcanize.bond.v1beta1.MsgWithdrawBond'
};
};
function createMsgCancelBond(
function createMsgCancelBond (
id: string,
signer: string
) {
@ -450,8 +450,8 @@ function createMsgCancelBond(
value: {
id,
signer
},
}
}
};
}
const protoCreateMsgCancelBond = (
@ -461,15 +461,15 @@ const protoCreateMsgCancelBond = (
const cancelBondMessage = new bondTx.vulcanize.bond.v1beta1.MsgCancelBond({
id,
signer
})
});
return {
message: cancelBondMessage,
path: 'vulcanize.bond.v1beta1.MsgCancelBond',
}
}
path: 'vulcanize.bond.v1beta1.MsgCancelBond'
};
};
function createMsgAssociateBond(
function createMsgAssociateBond (
recordId: string,
bondId: string,
signer: string
@ -480,8 +480,8 @@ function createMsgAssociateBond(
record_id: recordId,
bond_id: bondId,
signer
},
}
}
};
}
const protoCreateMsgAssociateBond = (
@ -493,15 +493,15 @@ const protoCreateMsgAssociateBond = (
record_id: recordId,
bond_id: bondId,
signer
})
});
return {
message: associateBondMessage,
path: 'vulcanize.registry.v1beta1.MsgAssociateBond',
}
}
path: 'vulcanize.registry.v1beta1.MsgAssociateBond'
};
};
function createMsgDissociateBond(
function createMsgDissociateBond (
recordId: string,
signer: string
) {
@ -510,8 +510,8 @@ function createMsgDissociateBond(
value: {
record_id: recordId,
signer
},
}
}
};
}
const protoCreateMsgDissociateBond = (
@ -521,15 +521,15 @@ const protoCreateMsgDissociateBond = (
const dissociateBondMessage = new registryTx.vulcanize.registry.v1beta1.MsgDissociateBond({
record_id: recordId,
signer
})
});
return {
message: dissociateBondMessage,
path: 'vulcanize.registry.v1beta1.MsgDissociateBond',
}
}
path: 'vulcanize.registry.v1beta1.MsgDissociateBond'
};
};
function createMsgDissociateRecords(
function createMsgDissociateRecords (
bondId: string,
signer: string
) {
@ -538,8 +538,8 @@ function createMsgDissociateRecords(
value: {
bond_id: bondId,
signer
},
}
}
};
}
const protoCreateMsgDissociateRecords = (
@ -549,15 +549,15 @@ const protoCreateMsgDissociateRecords = (
const dissociateRecordsMessage = new registryTx.vulcanize.registry.v1beta1.MsgDissociateRecords({
bond_id: bondId,
signer
})
});
return {
message: dissociateRecordsMessage,
path: 'vulcanize.registry.v1beta1.MsgDissociateRecords',
}
}
path: 'vulcanize.registry.v1beta1.MsgDissociateRecords'
};
};
function createMsgReAssociateRecords(
function createMsgReAssociateRecords (
newBondId: string,
oldBondId: string,
signer: string
@ -568,8 +568,8 @@ function createMsgReAssociateRecords(
new_bond_id: newBondId,
old_bond_id: oldBondId,
signer
},
}
}
};
}
const protoCreateMsgReAssociateRecords = (
@ -581,10 +581,10 @@ const protoCreateMsgReAssociateRecords = (
new_bond_id: newBondId,
old_bond_id: oldBondId,
signer
})
});
return {
message: reAssociateRecordsMessage,
path: 'vulcanize.registry.v1beta1.MsgReAssociateRecords',
}
}
path: 'vulcanize.registry.v1beta1.MsgReAssociateRecords'
};
};

View File

@ -1,42 +1,42 @@
import {
generateTypes,
} from '@tharsis/eip712'
generateTypes
} from '@tharsis/eip712';
import {
Chain,
Sender,
Fee,
} from '@tharsis/transactions'
Fee
} from '@tharsis/transactions';
import * as registryTx from '../proto/vulcanize/registry/v1beta1/tx'
import * as registry from '../proto/vulcanize/registry/v1beta1/registry'
import { createTx } from './util'
import { Payload } from '../types'
import * as registryTx from '../proto/vulcanize/registry/v1beta1/tx';
import * as registry from '../proto/vulcanize/registry/v1beta1/registry';
import { createTx } from './util';
import { Payload } from '../types';
const MSG_RESERVE_AUTHORITY_TYPES = {
MsgValue: [
{ name: 'name', type: 'string' },
{ name: 'signer', type: 'string' },
{ name: 'owner', type: 'string' },
],
}
{ name: 'owner', type: 'string' }
]
};
const MSG_SET_NAME_TYPES = {
MsgValue: [
{ name: 'crn', type: 'string' },
{ name: 'cid', type: 'string' },
{ name: 'signer', type: 'string' },
],
}
{ name: 'signer', type: 'string' }
]
};
const MSG_SET_RECORD_TYPES = {
MsgValue: [
{ name: 'bond_id', type: 'string' },
{ name: 'signer', type: 'string' },
{ name: 'payload', type: 'TypePayload' },
{ name: 'payload', type: 'TypePayload' }
],
TypePayload: [
{ name: 'record', type: 'TypePayloadRecord' },
{ name: 'signatures', type: 'TypePayloadSignatures[]' },
{ name: 'signatures', type: 'TypePayloadSignatures[]' }
],
TypePayloadRecord: [
{ name: 'id', type: 'string' },
@ -44,48 +44,48 @@ const MSG_SET_RECORD_TYPES = {
{ name: 'create_time', type: 'string' },
{ name: 'expiry_time', type: 'string' },
{ name: 'deleted', type: 'bool' },
{ name: 'attributes', type: 'bytes' },
{ name: 'attributes', type: 'bytes' }
],
TypePayloadSignatures: [
{ name: 'sig', type: 'string' },
{ name: 'pub_key', type: 'string' }
],
}
]
};
const MSG_SET_AUTHORITY_BOND_TYPES = {
MsgValue: [
{ name: 'name', type: 'string' },
{ name: 'bond_id', type: 'string' },
{ name: 'signer', type: 'string' },
],
}
{ name: 'signer', type: 'string' }
]
};
const MSG_DELETE_NAME_TYPES = {
MsgValue: [
{ name: 'crn', type: 'string' },
{ name: 'signer', type: 'string' },
],
}
{ name: 'signer', type: 'string' }
]
};
export const parseMsgSetRecordResponse = (data: string) => {
const responseBytes = Buffer.from(data, 'hex')
const responseBytes = Buffer.from(data, 'hex');
// TODO: Decode response using protobuf.
// const msgSetRecordResponse = nameserviceTx.vulcanize.nameservice.v1beta1.MsgSetRecordResponse.deserialize(responseBytes);
// return msgSetRecordResponse.toObject();
// Workaround as proto based decoding is not working.
const [_, id] = responseBytes.toString().split(';')
const [_, id] = responseBytes.toString().split(';');
return { id }
}
return { id };
};
export const NAMESERVICE_ERRORS = [
'Name already reserved.',
'Authority bond not found.',
'Name authority not found.',
'Access denied.',
]
'Access denied.'
];
export interface MessageMsgReserveAuthority {
name: string
@ -111,125 +111,125 @@ export interface MessageMsgDeleteName {
crn: string
}
export function createTxMsgReserveAuthority(
export function createTxMsgReserveAuthority (
chain: Chain,
sender: Sender,
fee: Fee,
memo: string,
params: MessageMsgReserveAuthority,
params: MessageMsgReserveAuthority
) {
const types = generateTypes(MSG_RESERVE_AUTHORITY_TYPES)
const types = generateTypes(MSG_RESERVE_AUTHORITY_TYPES);
const msg = createMsgReserveAuthority(
params.name,
sender.accountAddress,
params.owner
)
);
const msgCosmos = protoCreateMsgReserveAuthority(
params.name,
sender.accountAddress,
params.owner
)
);
return createTx(chain, sender, fee, memo, types, msg, msgCosmos)
return createTx(chain, sender, fee, memo, types, msg, msgCosmos);
}
export function createTxMsgSetName(
export function createTxMsgSetName (
chain: Chain,
sender: Sender,
fee: Fee,
memo: string,
params: MessageMsgSetName,
params: MessageMsgSetName
) {
const types = generateTypes(MSG_SET_NAME_TYPES)
const types = generateTypes(MSG_SET_NAME_TYPES);
const msg = createMsgSetName(
params.crn,
params.cid,
sender.accountAddress
)
);
const msgCosmos = protoCreateMsgSetName(
params.crn,
params.cid,
sender.accountAddress
)
);
return createTx(chain, sender, fee, memo, types, msg, msgCosmos)
return createTx(chain, sender, fee, memo, types, msg, msgCosmos);
}
export function createTxMsgSetRecord(
export function createTxMsgSetRecord (
chain: Chain,
sender: Sender,
fee: Fee,
memo: string,
params: MessageMsgSetRecord,
params: MessageMsgSetRecord
) {
const types = generateTypes(MSG_SET_RECORD_TYPES)
const types = generateTypes(MSG_SET_RECORD_TYPES);
const msg = createMsgSetRecord(
params.bondId,
params.payload,
sender.accountAddress
)
);
const msgCosmos = protoCreateMsgSetRecord(
params.bondId,
params.payload,
sender.accountAddress
)
);
return createTx(chain, sender, fee, memo, types, msg, msgCosmos)
return createTx(chain, sender, fee, memo, types, msg, msgCosmos);
}
export function createTxMsgSetAuthorityBond(
export function createTxMsgSetAuthorityBond (
chain: Chain,
sender: Sender,
fee: Fee,
memo: string,
params: MessageMsgSetAuthorityBond,
params: MessageMsgSetAuthorityBond
) {
const types = generateTypes(MSG_SET_AUTHORITY_BOND_TYPES)
const types = generateTypes(MSG_SET_AUTHORITY_BOND_TYPES);
const msg = createMsgSetAuthorityBond(
params.name,
params.bondId,
sender.accountAddress
)
);
const msgCosmos = protoCreateMsgSetAuthorityBond(
params.name,
params.bondId,
sender.accountAddress
)
);
return createTx(chain, sender, fee, memo, types, msg, msgCosmos)
return createTx(chain, sender, fee, memo, types, msg, msgCosmos);
}
export function createTxMsgDeleteName(
export function createTxMsgDeleteName (
chain: Chain,
sender: Sender,
fee: Fee,
memo: string,
params: MessageMsgDeleteName,
params: MessageMsgDeleteName
) {
const types = generateTypes(MSG_DELETE_NAME_TYPES)
const types = generateTypes(MSG_DELETE_NAME_TYPES);
const msg = createMsgDeleteName(
params.crn,
sender.accountAddress
)
);
const msgCosmos = protoCreateMsgDeleteName(
params.crn,
sender.accountAddress
)
);
return createTx(chain, sender, fee, memo, types, msg, msgCosmos)
return createTx(chain, sender, fee, memo, types, msg, msgCosmos);
}
function createMsgReserveAuthority(
function createMsgReserveAuthority (
name: string,
signer: string,
owner: string
@ -240,28 +240,28 @@ function createMsgReserveAuthority(
name,
signer,
owner
},
}
}
};
}
const protoCreateMsgReserveAuthority = (
name: string,
signer: string,
owner: string,
owner: string
) => {
const reserveAuthorityMessage = new registryTx.vulcanize.registry.v1beta1.MsgReserveAuthority({
name,
signer,
owner
})
});
return {
message: reserveAuthorityMessage,
path: 'vulcanize.registry.v1beta1.MsgReserveAuthority',
}
}
path: 'vulcanize.registry.v1beta1.MsgReserveAuthority'
};
};
function createMsgSetName(
function createMsgSetName (
crn: string,
cid: string,
signer: string
@ -272,8 +272,8 @@ function createMsgSetName(
crn,
cid,
signer
},
}
}
};
}
const protoCreateMsgSetName = (
@ -284,16 +284,16 @@ const protoCreateMsgSetName = (
const setNameMessage = new registryTx.vulcanize.registry.v1beta1.MsgSetName({
crn,
cid,
signer,
})
signer
});
return {
message: setNameMessage,
path: 'vulcanize.registry.v1beta1.MsgSetName',
}
}
path: 'vulcanize.registry.v1beta1.MsgSetName'
};
};
function createMsgSetRecord(
function createMsgSetRecord (
bondId: string,
payload: Payload,
signer: string
@ -304,8 +304,8 @@ function createMsgSetRecord(
bond_id: bondId,
signer,
payload: payload.serialize()
},
}
}
};
}
const protoCreateMsgSetRecord = (
@ -313,32 +313,32 @@ const protoCreateMsgSetRecord = (
payloadData: Payload,
signer: string
) => {
const record = new registry.vulcanize.registry.v1beta1.Record(payloadData.record.serialize())
const record = new registry.vulcanize.registry.v1beta1.Record(payloadData.record.serialize());
const signatures = payloadData.signatures.map(
signature => new registry.vulcanize.registry.v1beta1.Signature(
signature.serialize()
)
)
);
const payload = new registryTx.vulcanize.registry.v1beta1.Payload({
record,
signatures
})
});
const setNameMessage = new registryTx.vulcanize.registry.v1beta1.MsgSetRecord({
bond_id: bondId,
signer,
payload
})
});
return {
message: setNameMessage,
path: 'vulcanize.registry.v1beta1.MsgSetRecord',
}
}
path: 'vulcanize.registry.v1beta1.MsgSetRecord'
};
};
function createMsgSetAuthorityBond(
function createMsgSetAuthorityBond (
name: string,
bondId: string,
signer: string
@ -349,8 +349,8 @@ function createMsgSetAuthorityBond(
name,
bond_id: bondId,
signer
},
}
}
};
}
const protoCreateMsgSetAuthorityBond = (
@ -361,16 +361,16 @@ const protoCreateMsgSetAuthorityBond = (
const setAuthorityBondMessage = new registryTx.vulcanize.registry.v1beta1.MsgSetAuthorityBond({
name,
bond_id: bondId,
signer,
})
signer
});
return {
message: setAuthorityBondMessage,
path: 'vulcanize.registry.v1beta1.MsgSetAuthorityBond',
}
}
path: 'vulcanize.registry.v1beta1.MsgSetAuthorityBond'
};
};
function createMsgDeleteName(
function createMsgDeleteName (
crn: string,
signer: string
) {
@ -379,8 +379,8 @@ function createMsgDeleteName(
value: {
crn,
signer
},
}
}
};
}
const protoCreateMsgDeleteName = (
@ -389,11 +389,11 @@ const protoCreateMsgDeleteName = (
) => {
const deleteNameAutorityMessage = new registryTx.vulcanize.registry.v1beta1.MsgDeleteNameAuthority({
crn,
signer,
})
signer
});
return {
message: deleteNameAutorityMessage,
path: 'vulcanize.registry.v1beta1.MsgDeleteNameAuthority',
}
}
path: 'vulcanize.registry.v1beta1.MsgDeleteNameAuthority'
};
};

View File

@ -1,16 +1,16 @@
import { Message } from "google-protobuf";
import { Message } from 'google-protobuf';
import {
createEIP712,
generateFee,
generateMessage,
generateTypes,
} from '@tharsis/eip712'
generateTypes
} from '@tharsis/eip712';
import {
Chain,
Sender,
Fee,
} from '@tharsis/transactions'
import { createTransaction } from '@tharsis/proto'
Fee
} from '@tharsis/transactions';
import { createTransaction } from '@tharsis/proto';
interface Msg {
type: string
@ -36,16 +36,16 @@ export const createTx = (
memo: string,
messageTypes: Types,
msg: Msg,
msgCosmos: MsgCosmos,
msgCosmos: MsgCosmos
) => {
// EIP712
const feeObject = generateFee(
fee.amount,
fee.denom,
fee.gas,
sender.accountAddress,
)
const types = generateTypes(messageTypes)
sender.accountAddress
);
const types = generateTypes(messageTypes);
const messages = generateMessage(
sender.accountNumber.toString(),
@ -53,9 +53,9 @@ export const createTx = (
chain.cosmosChainId,
memo,
feeObject,
msg,
)
const eipToSign = createEIP712(types, chain.chainId, messages)
msg
);
const eipToSign = createEIP712(types, chain.chainId, messages);
// Cosmos
const tx = createTransaction(
@ -68,12 +68,12 @@ export const createTx = (
sender.pubkey,
sender.sequence,
sender.accountNumber,
chain.cosmosChainId,
)
chain.cosmosChainId
);
return {
signDirect: tx.signDirect,
legacyAmino: tx.legacyAmino,
eipToSign,
}
}
eipToSign
};
};

View File

@ -38,8 +38,8 @@ const nameserviceExpiryTests = () => {
},
privateKey,
fee
)
console.log("SetRecordResult: " + result.data.id)
);
console.log('SetRecordResult: ' + result.data.id);
const [record] = await registry.queryRecords({ type: 'WebsiteRegistrationRecord', version: watcher.record.version }, true);
recordExpiryTime = new Date(record.expiryTime);
@ -47,7 +47,7 @@ const nameserviceExpiryTests = () => {
expect(bond).toBeDefined();
expect(bond.balance).toHaveLength(1);
expect(bond.balance[0].quantity).toBe('2000000');
})
});
test('Reserve authority and set bond', async () => {
authorityName = `laconic-${Date.now()}`;
@ -62,41 +62,41 @@ const nameserviceExpiryTests = () => {
setTimeout(done, 60 * 1000);
});
test('Check record expiry time', async() => {
test('Check record expiry time', async () => {
const [record] = await registry.queryRecords({ type: 'WebsiteRegistrationRecord', version: watcher.record.version }, true);
const updatedExpiryTime = new Date();
expect(updatedExpiryTime.getTime()).toBeGreaterThan(recordExpiryTime.getTime());
recordExpiryTime = updatedExpiryTime;
})
});
test('Check authority expiry time', async() => {
test('Check authority expiry time', async () => {
const [authority] = await registry.lookupAuthorities([authorityName]);
const updatedExpiryTime = new Date();
expect(updatedExpiryTime.getTime()).toBeGreaterThan(authorityExpiryTime.getTime());
authorityExpiryTime = updatedExpiryTime;
})
});
test('Check bond balance', async () => {
const [bond] = await registry.getBondsByIds([bondId]);
console.log(bond)
console.log(bond);
expect(bond).toBeDefined();
expect(bond.balance).toHaveLength(0);
})
});
test('Wait for expiry duration', (done) => {
setTimeout(done, 60 * 1000);
});
test('Check record deleted without bond balance', async() => {
test('Check record deleted without bond balance', async () => {
const records = await registry.queryRecords({ type: 'WebsiteRegistrationRecord', version: watcher.record.version }, true);
expect(records).toHaveLength(0);
})
});
test('Check authority expired without bond balance', async() => {
test('Check authority expired without bond balance', async () => {
const [authority] = await registry.lookupAuthorities([authorityName]);
expect(authority.status).toBe('expired');
})
}
});
};
if (!process.env.TEST_NAMESERVICE_EXPIRY) {
// Required as jest complains if file has no tests.
@ -107,11 +107,10 @@ if (!process.env.TEST_NAMESERVICE_EXPIRY) {
TEST_REGISTRY_EXPIRY=true ./init.sh
Run tests:
yarn test:nameservice-expiry
*/
describe('Nameservice Expiry', nameserviceExpiryTests)
describe('Nameservice Expiry', nameserviceExpiryTests);
}

View File

@ -35,7 +35,7 @@ const namingTests = () => {
},
privateKey,
fee
)
);
watcherId = result.data.id;
});
@ -52,12 +52,11 @@ const namingTests = () => {
let crn: string;
beforeAll(async () => {
authorityName = `laconic-${Date.now()}`;
crn = `crn://${authorityName}/app/test`;
await registry.reserveAuthority({ name: authorityName }, privateKey, fee);
})
});
test('Lookup authority.', async () => {
const [record] = await registry.lookupAuthorities([authorityName]);
@ -77,8 +76,8 @@ const namingTests = () => {
});
test('Reserve already reserved authority', async () => {
await expect(registry.reserveAuthority({ name: authorityName }, privateKey, fee)).
rejects.toThrow('Name already reserved.');
await expect(registry.reserveAuthority({ name: authorityName }, privateKey, fee))
.rejects.toThrow('Name already reserved.');
});
test('Reserve sub-authority.', async () => {
@ -114,9 +113,9 @@ const namingTests = () => {
});
test('Set name for unbonded authority', async () => {
assert(watcherId)
await expect(registry.setName({ crn, cid: watcherId }, privateKey, fee)).
rejects.toThrow('Authority bond not found.');
assert(watcherId);
await expect(registry.setName({ crn, cid: watcherId }, privateKey, fee))
.rejects.toThrow('Authority bond not found.');
});
test('Set authority bond', async () => {
@ -203,7 +202,7 @@ const namingTests = () => {
},
privateKey,
fee
)
);
const updatedWatcherId = result.data.id;
await registry.setName({ crn, cid: updatedWatcherId }, privateKey, fee);

View File

@ -1,7 +1,7 @@
import assert from 'assert';
import axios from 'axios';
import graphqlClient from 'graphql.js'
import { get, set } from 'lodash'
import graphqlClient from 'graphql.js';
import { get, set } from 'lodash';
import { generateEndpointAccount, generateEndpointBroadcast } from '@tharsis/provider';
import { Util } from './util';
@ -97,13 +97,13 @@ const auctionFields = `
* Registry
*/
export class RegistryClient {
_restEndpoint: string
_graph: any
_restEndpoint: string;
_graph: any;
/**
* Get query result.
*/
static async getResult(query: any, key: string, modifier?: (rows: any[]) => {}) {
static async getResult (query: any, key: string, modifier?: (rows: any[]) => {}) {
const result = await query;
if (result && result[key] && result[key].length && result[key][0] !== null) {
if (modifier) {
@ -117,7 +117,7 @@ export class RegistryClient {
/**
* Prepare response attributes.
*/
static prepareAttributes(path: string) {
static prepareAttributes (path: string) {
return (rows: any[]) => {
const result = rows.map(r => {
set(r, path, Util.fromGQLAttributes(get(r, path)));
@ -130,7 +130,7 @@ export class RegistryClient {
/**
* New Client.
*/
constructor(gqlEndpoint: string, restEndpoint: string) {
constructor (gqlEndpoint: string, restEndpoint: string) {
assert(gqlEndpoint);
this._graph = graphqlClient(gqlEndpoint, {
method: 'POST',
@ -143,7 +143,7 @@ export class RegistryClient {
/**
* Get server status.
*/
async getStatus() {
async getStatus () {
const query = `query {
getStatus {
version
@ -189,7 +189,7 @@ export class RegistryClient {
/**
* Fetch Accounts.
*/
async getAccounts(addresses: string[]) {
async getAccounts (addresses: string[]) {
assert(addresses);
assert(addresses.length);
@ -216,7 +216,7 @@ export class RegistryClient {
/**
* Get records by ids.
*/
async getRecordsByIds(ids: string[], refs = false) {
async getRecordsByIds (ids: string[], refs = false) {
assert(ids);
assert(ids.length);
@ -243,7 +243,7 @@ export class RegistryClient {
/**
* Get records by attributes.
*/
async queryRecords(attributes: {[key: string]: any}, all = false, refs = false) {
async queryRecords (attributes: {[key: string]: any}, all = false, refs = false) {
if (!attributes) {
attributes = {};
}
@ -266,7 +266,7 @@ export class RegistryClient {
all
};
let result = (await this._graph(query)(variables))['queryRecords'];
let result = (await this._graph(query)(variables)).queryRecords;
result = RegistryClient.prepareAttributes('attributes')(result);
return result;
@ -275,7 +275,7 @@ export class RegistryClient {
/**
* Lookup authorities by names.
*/
async lookupAuthorities(names: string[], auction = false) {
async lookupAuthorities (names: string[], auction = false) {
assert(names.length);
const query = `query ($names: [String!]) {
@ -296,13 +296,13 @@ export class RegistryClient {
const result = await this._graph(query)(variables);
return result['lookupAuthorities'];
return result.lookupAuthorities;
}
/**
* Get auctions by ids.
*/
async getAuctionsByIds(ids: string[]) {
async getAuctionsByIds (ids: string[]) {
assert(ids);
assert(ids.length);
@ -322,7 +322,7 @@ export class RegistryClient {
/**
* Lookup names.
*/
async lookupNames(names: string[], history = false) {
async lookupNames (names: string[], history = false) {
assert(names.length);
const query = `query ($names: [String!]) {
@ -341,13 +341,13 @@ export class RegistryClient {
const result = await this._graph(query)(variables);
return result['lookupNames'];
return result.lookupNames;
}
/**
* Resolve names to records.
*/
async resolveNames(names: string[], refs = false) {
async resolveNames (names: string[], refs = false) {
assert(names.length);
const query = `query ($names: [String!]) {
@ -367,7 +367,7 @@ export class RegistryClient {
names
};
let result = (await this._graph(query)(variables))['resolveNames'];
let result = (await this._graph(query)(variables)).resolveNames;
result = RegistryClient.prepareAttributes('attributes')(result);
return result;
@ -376,7 +376,7 @@ export class RegistryClient {
/**
* Get bonds by ids.
*/
async getBondsByIds(ids: string[]) {
async getBondsByIds (ids: string[]) {
assert(ids);
assert(ids.length);
@ -401,7 +401,7 @@ export class RegistryClient {
/**
* Get records by attributes.
*/
async queryBonds(attributes = {}) {
async queryBonds (attributes = {}) {
const query = `query ($attributes: [KeyValueInput!]) {
queryBonds(attributes: $attributes) {
id
@ -423,14 +423,14 @@ export class RegistryClient {
/**
* Submit transaction.
*/
async submit(tx: string) {
async submit (tx: string) {
assert(tx);
// Broadcast transaction.
const { data } = await axios.post(
`${this._restEndpoint}${generateEndpointBroadcast()}`,
tx
)
);
return data;
}

View File

@ -60,7 +60,7 @@ describe('Querying', () => {
const records = await registry.queryRecords({ version, url, type: undefined }, true);
expect(records.length).toBe(1);
[ watcher ] = records;
[watcher] = records;
const { attributes: { version: recordVersion, url: recordName } } = watcher;
expect(recordVersion).toBe(version);
expect(recordName).toBe(url);
@ -77,7 +77,7 @@ describe('Querying', () => {
expect(record.id).toBe(watcher.id);
// temp fix
expect(record.attributes.repo_registration_record_cid).toBeDefined();
expect(record.attributes.repo_registration_record_cid).toHaveProperty("/");
expect(record.attributes.repo_registration_record_cid["/"]).toHaveLength(46);
expect(record.attributes.repo_registration_record_cid).toHaveProperty('/');
expect(record.attributes.repo_registration_record_cid['/']).toHaveLength(46);
});
});

View File

@ -31,17 +31,17 @@ export const getConfig = () => {
fee: {
amount: '40',
denom: 'aphoton',
gas: '400000',
gas: '400000'
}
}
};
};
// TODO: Merge both config
export const getLaconic2Config = () => {
return {
fee: {
amount: [{ denom: "photon", amount: "40" }],
gas: "400000",
amount: [{ denom: 'photon', amount: '40' }],
gas: '400000'
}
}
}
};
};

View File

@ -4,7 +4,7 @@ import {
signatureToWeb3Extension,
Chain,
Sender
} from '@tharsis/transactions'
} from '@tharsis/transactions';
import { Account } from './account';
@ -18,8 +18,8 @@ export const createTransaction = (message: any, account: Account, sender: Sender
// Sign transaction.
const signature = account.sign(message);
let extension = signatureToWeb3Extension(chain, sender, signature)
let extension = signatureToWeb3Extension(chain, sender, signature);
// Create the txRaw.
return createTxRawEIP712(message.legacyAmino.body, message.legacyAmino.authInfo, extension)
return createTxRawEIP712(message.legacyAmino.body, message.legacyAmino.authInfo, extension);
};

View File

@ -8,12 +8,12 @@ import { Util } from './util';
* Record.
*/
export class Record {
_record: any
_record: any;
/**
* New Record.
*/
constructor(record: any) {
constructor (record: any) {
assert(record);
const validator = new Validator();
@ -26,29 +26,29 @@ export class Record {
this._record = record;
}
get attributes() {
return Buffer.from(JSON.stringify(this._record), 'binary')
get attributes () {
return Buffer.from(JSON.stringify(this._record), 'binary');
}
/**
* Serialize record.
*/
serialize() {
serialize () {
return {
'id': '_',
'bond_id': '_',
'create_time': '_',
'expiry_time': '_',
id: '_',
bond_id: '_',
create_time: '_',
expiry_time: '_',
// Setting deleted as false (zero value) throws error in EIP712 signature verification.
'deleted': true,
'attributes': this.attributes,
}
deleted: true,
attributes: this.attributes
};
}
/**
* Get message to calculate record signature.
*/
getMessageToSign() {
getMessageToSign () {
return Util.sortJSON(this._record);
}
}
@ -57,13 +57,13 @@ export class Record {
* Record Signature.
*/
export class Signature {
_pubKey: string
_sig: string
_pubKey: string;
_sig: string;
/**
* New Signature.
*/
constructor(pubKey: string, sig: string) {
constructor (pubKey: string, sig: string) {
assert(pubKey);
assert(sig);
@ -74,10 +74,10 @@ export class Signature {
/**
* Serialize Signature.
*/
serialize() {
serialize () {
return Util.sortJSON({
'pub_key': this._pubKey,
'sig': this._sig
pub_key: this._pubKey,
sig: this._sig
});
}
}
@ -86,31 +86,31 @@ export class Signature {
* Message Payload.
*/
export class Payload {
_record: Record
_signatures: Signature[]
_record: Record;
_signatures: Signature[];
/**
* New Payload.
*/
constructor(record: Record, ...signatures: Signature[]) {
constructor (record: Record, ...signatures: Signature[]) {
assert(record);
this._record = record;
this._signatures = signatures;
}
get record() {
get record () {
return this._record;
}
get signatures() {
get signatures () {
return this._signatures;
}
/**
* Add message signature to payload.
*/
addSignature(signature: any) {
addSignature (signature: any) {
assert(signature);
this._signatures.push(signature);
@ -119,12 +119,12 @@ export class Payload {
/**
* Serialize Payload.
*/
serialize() {
serialize () {
// return Util.sortJSON({
// });
return {
'record': this._record.serialize(),
'signatures': this._signatures.map(s => s.serialize())
}
record: this._record.serialize(),
signatures: this._signatures.map(s => s.serialize())
};
}
}

View File

@ -1,4 +1,4 @@
import { EncodeObject, GeneratedType } from "@cosmjs/proto-signing";
import { EncodeObject, GeneratedType } from '@cosmjs/proto-signing';
import {
MsgCreateBond,
@ -9,17 +9,16 @@ import {
MsgRefillBondResponse,
MsgWithdrawBondResponse,
MsgCancelBondResponse
} from "../../../proto2/cerc/bond/v1/tx";
export const typeUrlMsgCreateBond = "/cerc.bond.v1.MsgCreateBond";
export const typeUrlMsgRefillBond = "/cerc.bond.v1.MsgRefillBond";
export const typeUrlMsgWithdrawBond = "/cerc.bond.v1.MsgWithdrawBond";
export const typeUrlMsgCancelBond = "/cerc.bond.v1.MsgCancelBond";
export const typeUrlMsgCreateBondResponse = "/cerc.bond.v1.MsgCreateBondResponse";
export const typeUrlMsgRefillBondResponse = "/cerc.bond.v1.MsgRefillBondResponse";
export const typeUrlMsgWithdrawBondResponse = "/cerc.bond.v1.MsgWithdrawBondResponse";
export const typeUrlMsgCancelBondResponse = "/cerc.bond.v1.MsgCancelBondResponse";
} from '../../../proto2/cerc/bond/v1/tx';
export const typeUrlMsgCreateBond = '/cerc.bond.v1.MsgCreateBond';
export const typeUrlMsgRefillBond = '/cerc.bond.v1.MsgRefillBond';
export const typeUrlMsgWithdrawBond = '/cerc.bond.v1.MsgWithdrawBond';
export const typeUrlMsgCancelBond = '/cerc.bond.v1.MsgCancelBond';
export const typeUrlMsgCreateBondResponse = '/cerc.bond.v1.MsgCreateBondResponse';
export const typeUrlMsgRefillBondResponse = '/cerc.bond.v1.MsgRefillBondResponse';
export const typeUrlMsgWithdrawBondResponse = '/cerc.bond.v1.MsgWithdrawBondResponse';
export const typeUrlMsgCancelBondResponse = '/cerc.bond.v1.MsgCancelBondResponse';
export const bondTypes: ReadonlyArray<[string, GeneratedType]> = [
[typeUrlMsgCreateBond, MsgCreateBond],
@ -29,25 +28,25 @@ export const bondTypes: ReadonlyArray<[string, GeneratedType]> = [
[typeUrlMsgWithdrawBond, MsgWithdrawBond],
[typeUrlMsgWithdrawBondResponse, MsgWithdrawBondResponse],
[typeUrlMsgCancelBond, MsgCancelBond],
[typeUrlMsgCancelBondResponse, MsgCancelBondResponse],
[typeUrlMsgCancelBondResponse, MsgCancelBondResponse]
];
export interface MsgCreateBondEncodeObject extends EncodeObject {
readonly typeUrl: "/cerc.bond.v1.MsgCreateBond";
readonly typeUrl: '/cerc.bond.v1.MsgCreateBond';
readonly value: Partial<MsgCreateBond>;
}
export interface MsgRefillBondEncodeObject extends EncodeObject {
readonly typeUrl: "/cerc.bond.v1.MsgRefillBond";
readonly typeUrl: '/cerc.bond.v1.MsgRefillBond';
readonly value: Partial<MsgRefillBond>;
}
export interface MsgWithdrawBondEncodeObject extends EncodeObject {
readonly typeUrl: "/cerc.bond.v1.MsgWithdrawBond";
readonly typeUrl: '/cerc.bond.v1.MsgWithdrawBond';
readonly value: Partial<MsgWithdrawBond>;
}
export interface MsgCancelBondEncodeObject extends EncodeObject {
readonly typeUrl: "/cerc.bond.v1.MsgCancelBond";
readonly typeUrl: '/cerc.bond.v1.MsgCancelBond';
readonly value: Partial<MsgCancelBond>;
}

View File

@ -34,15 +34,15 @@ const utilTests = () => {
},
privateKey,
fee
)
);
watcherId = result.data.id;
});
test('Generate content id.', async () => {
const cid = await Util.getContentId(watcher.record);
expect(cid).toBe(watcherId)
expect(cid).toBe(watcherId);
});
}
};
describe('Util', utilTests);

View File

@ -1,7 +1,7 @@
import * as Block from 'multiformats/block'
import { sha256 as hasher } from 'multiformats/hashes/sha2'
import * as dagCBOR from '@ipld/dag-cbor'
import * as dagJSON from '@ipld/dag-json'
import * as Block from 'multiformats/block';
import { sha256 as hasher } from 'multiformats/hashes/sha2';
import * as dagCBOR from '@ipld/dag-cbor';
import * as dagJSON from '@ipld/dag-json';
/**
* Utils
@ -10,7 +10,7 @@ export class Util {
/**
* Sorts JSON object.
*/
static sortJSON(obj: any) {
static sortJSON (obj: any) {
if (obj instanceof Array) {
for (let i = 0; i < obj.length; i++) {
obj[i] = Util.sortJSON(obj[i]);
@ -32,7 +32,7 @@ export class Util {
/**
* Marshal object into gql 'attributes' variable.
*/
static toGQLAttributes(obj: any) {
static toGQLAttributes (obj: any) {
const vars: any[] = [];
Object.keys(obj).forEach(key => {
const value = this.toGQLValue(obj[key]);
@ -44,38 +44,38 @@ export class Util {
return vars;
}
static toGQLValue(obj: any) {
if (obj === null) {
return null;
}
let type: string = typeof obj;
switch (type) {
case 'number':
type = (obj % 1 === 0) ? 'int' : 'float';
return { [type]: obj };
case 'string':
return { 'string': obj };
case 'boolean':
return { 'boolean': obj };
case 'object':
if (obj['/'] !== undefined) {
return { 'link': obj['/'] };
}
if (obj instanceof Array) {
return { 'array': obj };
}
return { 'map': obj };
case 'undefined':
return undefined;
default:
throw new Error(`Unknown object type '${type}': ${obj}`);
}
static toGQLValue (obj: any) {
if (obj === null) {
return null;
}
let type: string = typeof obj;
switch (type) {
case 'number':
type = (obj % 1 === 0) ? 'int' : 'float';
return { [type]: obj };
case 'string':
return { string: obj };
case 'boolean':
return { boolean: obj };
case 'object':
if (obj['/'] !== undefined) {
return { link: obj['/'] };
}
if (obj instanceof Array) {
return { array: obj };
}
return { map: obj };
case 'undefined':
return undefined;
default:
throw new Error(`Unknown object type '${type}': ${obj}`);
}
}
/**
* Unmarshal attributes array to object.
*/
static fromGQLAttributes(attributes: any[] = []) {
static fromGQLAttributes (attributes: any[] = []) {
const res: {[key: string]: any} = {};
attributes.forEach(attr => {
@ -85,7 +85,7 @@ export class Util {
return res;
}
static fromGQLValue(obj: any) {
static fromGQLValue (obj: any) {
// Get first non-null key
const present = Object.keys(obj).find(k => obj[k] !== null);
if (present === undefined) {
@ -105,15 +105,15 @@ export class Util {
/**
* Get record content ID.
*/
static async getContentId(record: any) {
const serialized = dagJSON.encode(record)
const recordData = dagJSON.decode(serialized)
static async getContentId (record: any) {
const serialized = dagJSON.encode(record);
const recordData = dagJSON.decode(serialized);
const block = await Block.encode({
value: recordData,
codec: dagCBOR,
hasher
})
});
return block.cid.toString();
}

1352
yarn.lock

File diff suppressed because it is too large Load Diff