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 = { module.exports = {
preset: 'ts-jest', preset: 'ts-jest',
testEnvironment: 'node', testEnvironment: 'node',
setupFiles: ["dotenv/config"] setupFiles: ['dotenv/config']
}; };

View File

@ -11,8 +11,18 @@
"@types/lodash": "^4.14.181", "@types/lodash": "^4.14.181",
"@types/semver": "^7.3.9", "@types/semver": "^7.3.9",
"@types/tiny-secp256k1": "1.0.0", "@types/tiny-secp256k1": "1.0.0",
"@typescript-eslint/eslint-plugin": "^5.47.1",
"@typescript-eslint/parser": "^5.47.1",
"dotenv": "^16.0.0", "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", "google-protobuf": "^3.21.0",
"husky": "^9.0.11",
"jest": "29.0.0", "jest": "29.0.0",
"ts-jest": "^29.0.2", "ts-jest": "^29.0.2",
"ts-proto": "1.121.6", "ts-proto": "1.121.6",
@ -55,6 +65,8 @@
"test": "jest --runInBand --verbose --testPathPattern=src", "test": "jest --runInBand --verbose --testPathPattern=src",
"test:auctions": "TEST_AUCTIONS_ENABLED=1 jest --runInBand --verbose src/auction.test.ts", "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", "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 { utils } from 'ethers';
import { sha256 } from 'js-sha256'; import { sha256 } from 'js-sha256';
import { MessageTypes, signTypedData, SignTypedDataVersion } from '@metamask/eth-sig-util'; 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 { fromHex, toHex } from '@cosmjs/encoding';
import { ethToEthermint } from "@tharsis/address-converter" import { ethToEthermint } from '@tharsis/address-converter';
import { encodeSecp256k1Pubkey } from '@cosmjs/amino'; import { encodeSecp256k1Pubkey } from '@cosmjs/amino';
import { DirectSecp256k1Wallet } from "@cosmjs/proto-signing"; import { DirectSecp256k1Wallet } from '@cosmjs/proto-signing';
import { Payload, Signature } from './types'; import { Payload, Signature } from './types';
const AMINO_PREFIX = 'EB5AE98721'; const AMINO_PREFIX = 'EB5AE98721';
const HDPATH = "m/44'/60'/0'/0"; const HDPATH = "m/44'/60'/0'/0";
const ACCOUNT_PREFIX = "laconic"; const ACCOUNT_PREFIX = 'laconic';
const bip32 = BIP32Factory(ecc); const bip32 = BIP32Factory(ecc);
@ -33,27 +33,27 @@ interface TypedMessageDomain {
* Registry account. * Registry account.
*/ */
export class Account { export class Account {
_privateKey: Buffer _privateKey: Buffer;
_publicKey!: Uint8Array _publicKey!: Uint8Array;
_encodedPubkey!: string _encodedPubkey!: string;
_formattedCosmosAddress!: string _formattedCosmosAddress!: string;
_registryPublicKey!: string _registryPublicKey!: string;
_registryAddress!: string _registryAddress!: string;
_ethAddress!: string _ethAddress!: string;
_wallet!: DirectSecp256k1Wallet _wallet!: DirectSecp256k1Wallet;
_address!: string _address!: string;
/** /**
* Generate bip39 mnemonic. * Generate bip39 mnemonic.
*/ */
static generateMnemonic() { static generateMnemonic () {
return bip39.generateMnemonic(); return bip39.generateMnemonic();
} }
/** /**
* Generate private key from mnemonic. * Generate private key from mnemonic.
*/ */
static async generateFromMnemonic(mnemonic: string) { static async generateFromMnemonic (mnemonic: string) {
assert(mnemonic); assert(mnemonic);
const seed = await bip39.mnemonicToSeed(mnemonic); const seed = await bip39.mnemonicToSeed(mnemonic);
@ -68,36 +68,36 @@ export class Account {
/** /**
* New Account. * New Account.
*/ */
constructor(privateKey: Buffer) { constructor (privateKey: Buffer) {
assert(privateKey); assert(privateKey);
this._privateKey = privateKey; this._privateKey = privateKey;
} }
get privateKey() { get privateKey () {
return this._privateKey; return this._privateKey;
} }
get encodedPubkey() { get encodedPubkey () {
return this._encodedPubkey; return this._encodedPubkey;
} }
get formattedCosmosAddress() { get formattedCosmosAddress () {
return this._formattedCosmosAddress; return this._formattedCosmosAddress;
} }
get registryPublicKey() { get registryPublicKey () {
return this._registryPublicKey; return this._registryPublicKey;
} }
get registryAddress() { get registryAddress () {
return this._registryAddress; return this._registryAddress;
} }
get address() { get address () {
return this._address; return this._address;
} }
get wallet() { get wallet () {
return this._wallet; return this._wallet;
} }
@ -107,14 +107,14 @@ export class Account {
ACCOUNT_PREFIX ACCOUNT_PREFIX
); );
this._address = (await this._wallet.getAccounts())[0].address this._address = (await this._wallet.getAccounts())[0].address;
// Generate public key. // Generate public key.
this._publicKey = secp256k1.publicKeyCreate(this._privateKey) this._publicKey = secp256k1.publicKeyCreate(this._privateKey);
this._encodedPubkey = encodeSecp256k1Pubkey(this._publicKey).value this._encodedPubkey = encodeSecp256k1Pubkey(this._publicKey).value;
// 2. Generate eth address. // 2. Generate eth address.
this._ethAddress = utils.computeAddress(this._publicKey) this._ethAddress = utils.computeAddress(this._publicKey);
// 3. Generate cosmos-sdk formatted address. // 3. Generate cosmos-sdk formatted address.
this._formattedCosmosAddress = ethToEthermint(this._ethAddress); this._formattedCosmosAddress = ethToEthermint(this._ethAddress);
@ -131,21 +131,21 @@ export class Account {
/** /**
* Get private key. * Get private key.
*/ */
getPrivateKey() { getPrivateKey () {
return this._privateKey.toString('hex'); return this._privateKey.toString('hex');
} }
/** /**
* Get cosmos address. * Get cosmos address.
*/ */
getCosmosAddress() { getCosmosAddress () {
return this._formattedCosmosAddress; return this._formattedCosmosAddress;
} }
/** /**
* Get record signature. * Get record signature.
*/ */
async signRecord(record: any) { async signRecord (record: any) {
assert(record); assert(record);
const recordAsJson = canonicalStringify(record); const recordAsJson = canonicalStringify(record);
@ -162,14 +162,14 @@ export class Account {
return Buffer.from(sigObj.signature); return Buffer.from(sigObj.signature);
} }
async signPayload(payload: Payload) { async signPayload (payload: Payload) {
assert(payload); assert(payload);
const { record } = payload; const { record } = payload;
const messageToSign = record.getMessageToSign(); const messageToSign = record.getMessageToSign();
const sig = await this.signRecord(messageToSign); const sig = await this.signRecord(messageToSign);
assert(this.registryPublicKey) assert(this.registryPublicKey);
const signature = new Signature(this.registryPublicKey, sig.toString('base64')); const signature = new Signature(this.registryPublicKey, sig.toString('base64'));
payload.addSignature(signature); payload.addSignature(signature);
@ -179,7 +179,7 @@ export class Account {
/** /**
* Sign message. * Sign message.
*/ */
sign(message: any) { sign (message: any) {
assert(message); assert(message);
const eipMessageDomain: any = message.eipToSign.domain; const eipMessageDomain: any = message.eipToSign.domain;
@ -192,7 +192,7 @@ export class Account {
}, },
privateKey: this._privateKey, privateKey: this._privateKey,
version: SignTypedDataVersion.V4 version: SignTypedDataVersion.V4
}) });
return signature; return signature;
} }

View File

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

View File

@ -2,13 +2,13 @@ import path from 'path';
import { Registry } from './index'; import { Registry } from './index';
import { ensureUpdatedConfig, getConfig, getLaconic2Config } from './testing/helper'; 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 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 { chainId, restEndpoint, gqlEndpoint, privateKey, fee } = getConfig();
const { fee: laconic2Fee } = getLaconic2Config() const { fee: laconic2Fee } = getLaconic2Config();
jest.setTimeout(90 * 1000); jest.setTimeout(90 * 1000);
@ -32,7 +32,7 @@ const bondTests = () => {
}); });
describe('With bond created', () => { describe('With bond created', () => {
let bond1: any let bond1: any;
beforeAll(async () => { beforeAll(async () => {
let bondId1 = await registry.getNextBondId(privateKey); let bondId1 = await registry.getNextBondId(privateKey);
@ -67,7 +67,7 @@ const bondTests = () => {
}); });
test('Refill bond.', async () => { test('Refill bond.', async () => {
const refillAmount = "500"; const refillAmount = '500';
const total = (parseInt(BOND_AMOUNT) + parseInt(refillAmount)).toString(); const total = (parseInt(BOND_AMOUNT) + parseInt(refillAmount)).toString();
await registry.refillBond({ id: bond1.id, denom: DENOM, amount: refillAmount }, privateKey, laconic2Fee); await registry.refillBond({ id: bond1.id, denom: DENOM, amount: refillAmount }, privateKey, laconic2Fee);
const [bond] = await registry.getBondsByIds([bond1.id]); const [bond] = await registry.getBondsByIds([bond1.id]);
@ -78,7 +78,7 @@ const bondTests = () => {
}); });
test('Withdraw bond.', async () => { 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]); const [bond] = await registry.getBondsByIds([bond1.id]);
expect(bond).toBeDefined(); expect(bond).toBeDefined();
expect(bond.id).toBe(bond1.id); expect(bond.id).toBe(bond1.id);
@ -89,11 +89,10 @@ const bondTests = () => {
test('Cancel bond.', async () => { test('Cancel bond.', async () => {
await registry.cancelBond({ id: bond1.id }, privateKey, laconic2Fee); await registry.cancelBond({ id: bond1.id }, privateKey, laconic2Fee);
const [bond] = await registry.getBondsByIds([bond1.id]); const [bond] = await registry.getBondsByIds([bond1.id]);
expect(bond.id).toBe(""); expect(bond.id).toBe('');
expect(bond.owner).toBe(""); expect(bond.owner).toBe('');
expect(bond.balance).toHaveLength(0); expect(bond.balance).toHaveLength(0);
}); });
}); });
test('Associate/Dissociate bond.', async () => { 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 () => { beforeAll(async () => {
registry = new Registry(gqlEndpoint, restEndpoint, chainId); 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 account = new Account(Buffer.from(privateKey, 'hex'));
const accounts = await registry.getAccounts([account.formattedCosmosAddress]); const accounts = await registry.getAccounts([account.formattedCosmosAddress]);
expect(accounts).toHaveLength(1) expect(accounts).toHaveLength(1);
const [accountObj] = accounts; const [accountObj] = accounts;
expect(accountObj.address).toBe(account.formattedCosmosAddress); expect(accountObj.address).toBe(account.formattedCosmosAddress);
expect(accountObj.pubKey).toBe(account.encodedPubkey); expect(accountObj.pubKey).toBe(account.encodedPubkey);
expect(accountObj.number).toBe('0'); expect(accountObj.number).toBe('0');
expect(accountObj.sequence).toBeDefined(); expect(accountObj.sequence).toBeDefined();
expect(accountObj.balance).toHaveLength(1); expect(accountObj.balance).toHaveLength(1);
const [{ type, quantity }] = accountObj.balance const [{ type, quantity }] = accountObj.balance;
expect(type).toBe('aphoton'); expect(type).toBe('aphoton');
expect(quantity).toBeDefined(); expect(quantity).toBeDefined();
}) });
test('Get account balance.', async() => { test('Get account balance.', async () => {
const mnenonic1 = Account.generateMnemonic(); const mnenonic1 = Account.generateMnemonic();
const otherAccount = await Account.generateFromMnemonic(mnenonic1); const otherAccount = await Account.generateFromMnemonic(mnenonic1);
await registry.sendCoins({ denom: 'aphoton', amount: '100000000', destinationAddress: otherAccount.formattedCosmosAddress }, privateKey, fee); 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]); const [accountObj] = await registry.getAccounts([otherAccount.formattedCosmosAddress]);
expect(accountObj).toBeDefined(); expect(accountObj).toBeDefined();
expect(accountObj.address).toBe(otherAccount.formattedCosmosAddress); expect(accountObj.address).toBe(otherAccount.formattedCosmosAddress);
const [{ type, quantity }] = accountObj.balance const [{ type, quantity }] = accountObj.balance;
expect(type).toBe('aphoton'); expect(type).toBe('aphoton');
expect(quantity).toBe('100000000'); expect(quantity).toBe('100000000');
}) });
} };
describe('Registry', registryTests); describe('Registry', registryTests);

View File

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

View File

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

View File

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

View File

@ -1,42 +1,42 @@
import { import {
generateTypes, generateTypes
} from '@tharsis/eip712' } from '@tharsis/eip712';
import { import {
Chain, Chain,
Sender, Sender,
Fee, Fee
} from '@tharsis/transactions' } from '@tharsis/transactions';
import * as registryTx from '../proto/vulcanize/registry/v1beta1/tx' import * as registryTx from '../proto/vulcanize/registry/v1beta1/tx';
import * as registry from '../proto/vulcanize/registry/v1beta1/registry' import * as registry from '../proto/vulcanize/registry/v1beta1/registry';
import { createTx } from './util' import { createTx } from './util';
import { Payload } from '../types' import { Payload } from '../types';
const MSG_RESERVE_AUTHORITY_TYPES = { const MSG_RESERVE_AUTHORITY_TYPES = {
MsgValue: [ MsgValue: [
{ name: 'name', type: 'string' }, { name: 'name', type: 'string' },
{ name: 'signer', type: 'string' }, { name: 'signer', type: 'string' },
{ name: 'owner', type: 'string' }, { name: 'owner', type: 'string' }
], ]
} };
const MSG_SET_NAME_TYPES = { const MSG_SET_NAME_TYPES = {
MsgValue: [ MsgValue: [
{ name: 'crn', type: 'string' }, { name: 'crn', type: 'string' },
{ name: 'cid', type: 'string' }, { name: 'cid', type: 'string' },
{ name: 'signer', type: 'string' }, { name: 'signer', type: 'string' }
], ]
} };
const MSG_SET_RECORD_TYPES = { const MSG_SET_RECORD_TYPES = {
MsgValue: [ MsgValue: [
{ name: 'bond_id', type: 'string' }, { name: 'bond_id', type: 'string' },
{ name: 'signer', type: 'string' }, { name: 'signer', type: 'string' },
{ name: 'payload', type: 'TypePayload' }, { name: 'payload', type: 'TypePayload' }
], ],
TypePayload: [ TypePayload: [
{ name: 'record', type: 'TypePayloadRecord' }, { name: 'record', type: 'TypePayloadRecord' },
{ name: 'signatures', type: 'TypePayloadSignatures[]' }, { name: 'signatures', type: 'TypePayloadSignatures[]' }
], ],
TypePayloadRecord: [ TypePayloadRecord: [
{ name: 'id', type: 'string' }, { name: 'id', type: 'string' },
@ -44,48 +44,48 @@ const MSG_SET_RECORD_TYPES = {
{ name: 'create_time', type: 'string' }, { name: 'create_time', type: 'string' },
{ name: 'expiry_time', type: 'string' }, { name: 'expiry_time', type: 'string' },
{ name: 'deleted', type: 'bool' }, { name: 'deleted', type: 'bool' },
{ name: 'attributes', type: 'bytes' }, { name: 'attributes', type: 'bytes' }
], ],
TypePayloadSignatures: [ TypePayloadSignatures: [
{ name: 'sig', type: 'string' }, { name: 'sig', type: 'string' },
{ name: 'pub_key', type: 'string' } { name: 'pub_key', type: 'string' }
], ]
} };
const MSG_SET_AUTHORITY_BOND_TYPES = { const MSG_SET_AUTHORITY_BOND_TYPES = {
MsgValue: [ MsgValue: [
{ name: 'name', type: 'string' }, { name: 'name', type: 'string' },
{ name: 'bond_id', type: 'string' }, { name: 'bond_id', type: 'string' },
{ name: 'signer', type: 'string' }, { name: 'signer', type: 'string' }
], ]
} };
const MSG_DELETE_NAME_TYPES = { const MSG_DELETE_NAME_TYPES = {
MsgValue: [ MsgValue: [
{ name: 'crn', type: 'string' }, { name: 'crn', type: 'string' },
{ name: 'signer', type: 'string' }, { name: 'signer', type: 'string' }
], ]
} };
export const parseMsgSetRecordResponse = (data: string) => { export const parseMsgSetRecordResponse = (data: string) => {
const responseBytes = Buffer.from(data, 'hex') const responseBytes = Buffer.from(data, 'hex');
// TODO: Decode response using protobuf. // TODO: Decode response using protobuf.
// const msgSetRecordResponse = nameserviceTx.vulcanize.nameservice.v1beta1.MsgSetRecordResponse.deserialize(responseBytes); // const msgSetRecordResponse = nameserviceTx.vulcanize.nameservice.v1beta1.MsgSetRecordResponse.deserialize(responseBytes);
// return msgSetRecordResponse.toObject(); // return msgSetRecordResponse.toObject();
// Workaround as proto based decoding is not working. // 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 = [ export const NAMESERVICE_ERRORS = [
'Name already reserved.', 'Name already reserved.',
'Authority bond not found.', 'Authority bond not found.',
'Name authority not found.', 'Name authority not found.',
'Access denied.', 'Access denied.'
] ];
export interface MessageMsgReserveAuthority { export interface MessageMsgReserveAuthority {
name: string name: string
@ -111,125 +111,125 @@ export interface MessageMsgDeleteName {
crn: string crn: string
} }
export function createTxMsgReserveAuthority( export function createTxMsgReserveAuthority (
chain: Chain, chain: Chain,
sender: Sender, sender: Sender,
fee: Fee, fee: Fee,
memo: string, memo: string,
params: MessageMsgReserveAuthority, params: MessageMsgReserveAuthority
) { ) {
const types = generateTypes(MSG_RESERVE_AUTHORITY_TYPES) const types = generateTypes(MSG_RESERVE_AUTHORITY_TYPES);
const msg = createMsgReserveAuthority( const msg = createMsgReserveAuthority(
params.name, params.name,
sender.accountAddress, sender.accountAddress,
params.owner params.owner
) );
const msgCosmos = protoCreateMsgReserveAuthority( const msgCosmos = protoCreateMsgReserveAuthority(
params.name, params.name,
sender.accountAddress, sender.accountAddress,
params.owner 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, chain: Chain,
sender: Sender, sender: Sender,
fee: Fee, fee: Fee,
memo: string, memo: string,
params: MessageMsgSetName, params: MessageMsgSetName
) { ) {
const types = generateTypes(MSG_SET_NAME_TYPES) const types = generateTypes(MSG_SET_NAME_TYPES);
const msg = createMsgSetName( const msg = createMsgSetName(
params.crn, params.crn,
params.cid, params.cid,
sender.accountAddress sender.accountAddress
) );
const msgCosmos = protoCreateMsgSetName( const msgCosmos = protoCreateMsgSetName(
params.crn, params.crn,
params.cid, params.cid,
sender.accountAddress 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, chain: Chain,
sender: Sender, sender: Sender,
fee: Fee, fee: Fee,
memo: string, memo: string,
params: MessageMsgSetRecord, params: MessageMsgSetRecord
) { ) {
const types = generateTypes(MSG_SET_RECORD_TYPES) const types = generateTypes(MSG_SET_RECORD_TYPES);
const msg = createMsgSetRecord( const msg = createMsgSetRecord(
params.bondId, params.bondId,
params.payload, params.payload,
sender.accountAddress sender.accountAddress
) );
const msgCosmos = protoCreateMsgSetRecord( const msgCosmos = protoCreateMsgSetRecord(
params.bondId, params.bondId,
params.payload, params.payload,
sender.accountAddress 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, chain: Chain,
sender: Sender, sender: Sender,
fee: Fee, fee: Fee,
memo: string, 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( const msg = createMsgSetAuthorityBond(
params.name, params.name,
params.bondId, params.bondId,
sender.accountAddress sender.accountAddress
) );
const msgCosmos = protoCreateMsgSetAuthorityBond( const msgCosmos = protoCreateMsgSetAuthorityBond(
params.name, params.name,
params.bondId, params.bondId,
sender.accountAddress 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, chain: Chain,
sender: Sender, sender: Sender,
fee: Fee, fee: Fee,
memo: string, memo: string,
params: MessageMsgDeleteName, params: MessageMsgDeleteName
) { ) {
const types = generateTypes(MSG_DELETE_NAME_TYPES) const types = generateTypes(MSG_DELETE_NAME_TYPES);
const msg = createMsgDeleteName( const msg = createMsgDeleteName(
params.crn, params.crn,
sender.accountAddress sender.accountAddress
) );
const msgCosmos = protoCreateMsgDeleteName( const msgCosmos = protoCreateMsgDeleteName(
params.crn, params.crn,
sender.accountAddress 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, name: string,
signer: string, signer: string,
owner: string owner: string
@ -240,28 +240,28 @@ function createMsgReserveAuthority(
name, name,
signer, signer,
owner owner
}, }
} };
} }
const protoCreateMsgReserveAuthority = ( const protoCreateMsgReserveAuthority = (
name: string, name: string,
signer: string, signer: string,
owner: string, owner: string
) => { ) => {
const reserveAuthorityMessage = new registryTx.vulcanize.registry.v1beta1.MsgReserveAuthority({ const reserveAuthorityMessage = new registryTx.vulcanize.registry.v1beta1.MsgReserveAuthority({
name, name,
signer, signer,
owner owner
}) });
return { return {
message: reserveAuthorityMessage, message: reserveAuthorityMessage,
path: 'vulcanize.registry.v1beta1.MsgReserveAuthority', path: 'vulcanize.registry.v1beta1.MsgReserveAuthority'
} };
} };
function createMsgSetName( function createMsgSetName (
crn: string, crn: string,
cid: string, cid: string,
signer: string signer: string
@ -272,8 +272,8 @@ function createMsgSetName(
crn, crn,
cid, cid,
signer signer
}, }
} };
} }
const protoCreateMsgSetName = ( const protoCreateMsgSetName = (
@ -284,16 +284,16 @@ const protoCreateMsgSetName = (
const setNameMessage = new registryTx.vulcanize.registry.v1beta1.MsgSetName({ const setNameMessage = new registryTx.vulcanize.registry.v1beta1.MsgSetName({
crn, crn,
cid, cid,
signer, signer
}) });
return { return {
message: setNameMessage, message: setNameMessage,
path: 'vulcanize.registry.v1beta1.MsgSetName', path: 'vulcanize.registry.v1beta1.MsgSetName'
} };
} };
function createMsgSetRecord( function createMsgSetRecord (
bondId: string, bondId: string,
payload: Payload, payload: Payload,
signer: string signer: string
@ -304,8 +304,8 @@ function createMsgSetRecord(
bond_id: bondId, bond_id: bondId,
signer, signer,
payload: payload.serialize() payload: payload.serialize()
}, }
} };
} }
const protoCreateMsgSetRecord = ( const protoCreateMsgSetRecord = (
@ -313,32 +313,32 @@ const protoCreateMsgSetRecord = (
payloadData: Payload, payloadData: Payload,
signer: string 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( const signatures = payloadData.signatures.map(
signature => new registry.vulcanize.registry.v1beta1.Signature( signature => new registry.vulcanize.registry.v1beta1.Signature(
signature.serialize() signature.serialize()
) )
) );
const payload = new registryTx.vulcanize.registry.v1beta1.Payload({ const payload = new registryTx.vulcanize.registry.v1beta1.Payload({
record, record,
signatures signatures
}) });
const setNameMessage = new registryTx.vulcanize.registry.v1beta1.MsgSetRecord({ const setNameMessage = new registryTx.vulcanize.registry.v1beta1.MsgSetRecord({
bond_id: bondId, bond_id: bondId,
signer, signer,
payload payload
}) });
return { return {
message: setNameMessage, message: setNameMessage,
path: 'vulcanize.registry.v1beta1.MsgSetRecord', path: 'vulcanize.registry.v1beta1.MsgSetRecord'
} };
} };
function createMsgSetAuthorityBond( function createMsgSetAuthorityBond (
name: string, name: string,
bondId: string, bondId: string,
signer: string signer: string
@ -349,8 +349,8 @@ function createMsgSetAuthorityBond(
name, name,
bond_id: bondId, bond_id: bondId,
signer signer
}, }
} };
} }
const protoCreateMsgSetAuthorityBond = ( const protoCreateMsgSetAuthorityBond = (
@ -361,16 +361,16 @@ const protoCreateMsgSetAuthorityBond = (
const setAuthorityBondMessage = new registryTx.vulcanize.registry.v1beta1.MsgSetAuthorityBond({ const setAuthorityBondMessage = new registryTx.vulcanize.registry.v1beta1.MsgSetAuthorityBond({
name, name,
bond_id: bondId, bond_id: bondId,
signer, signer
}) });
return { return {
message: setAuthorityBondMessage, message: setAuthorityBondMessage,
path: 'vulcanize.registry.v1beta1.MsgSetAuthorityBond', path: 'vulcanize.registry.v1beta1.MsgSetAuthorityBond'
} };
} };
function createMsgDeleteName( function createMsgDeleteName (
crn: string, crn: string,
signer: string signer: string
) { ) {
@ -379,8 +379,8 @@ function createMsgDeleteName(
value: { value: {
crn, crn,
signer signer
}, }
} };
} }
const protoCreateMsgDeleteName = ( const protoCreateMsgDeleteName = (
@ -389,11 +389,11 @@ const protoCreateMsgDeleteName = (
) => { ) => {
const deleteNameAutorityMessage = new registryTx.vulcanize.registry.v1beta1.MsgDeleteNameAuthority({ const deleteNameAutorityMessage = new registryTx.vulcanize.registry.v1beta1.MsgDeleteNameAuthority({
crn, crn,
signer, signer
}) });
return { return {
message: deleteNameAutorityMessage, 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 { import {
createEIP712, createEIP712,
generateFee, generateFee,
generateMessage, generateMessage,
generateTypes, generateTypes
} from '@tharsis/eip712' } from '@tharsis/eip712';
import { import {
Chain, Chain,
Sender, Sender,
Fee, Fee
} from '@tharsis/transactions' } from '@tharsis/transactions';
import { createTransaction } from '@tharsis/proto' import { createTransaction } from '@tharsis/proto';
interface Msg { interface Msg {
type: string type: string
@ -36,16 +36,16 @@ export const createTx = (
memo: string, memo: string,
messageTypes: Types, messageTypes: Types,
msg: Msg, msg: Msg,
msgCosmos: MsgCosmos, msgCosmos: MsgCosmos
) => { ) => {
// EIP712 // EIP712
const feeObject = generateFee( const feeObject = generateFee(
fee.amount, fee.amount,
fee.denom, fee.denom,
fee.gas, fee.gas,
sender.accountAddress, sender.accountAddress
) );
const types = generateTypes(messageTypes) const types = generateTypes(messageTypes);
const messages = generateMessage( const messages = generateMessage(
sender.accountNumber.toString(), sender.accountNumber.toString(),
@ -53,9 +53,9 @@ export const createTx = (
chain.cosmosChainId, chain.cosmosChainId,
memo, memo,
feeObject, feeObject,
msg, msg
) );
const eipToSign = createEIP712(types, chain.chainId, messages) const eipToSign = createEIP712(types, chain.chainId, messages);
// Cosmos // Cosmos
const tx = createTransaction( const tx = createTransaction(
@ -68,12 +68,12 @@ export const createTx = (
sender.pubkey, sender.pubkey,
sender.sequence, sender.sequence,
sender.accountNumber, sender.accountNumber,
chain.cosmosChainId, chain.cosmosChainId
) );
return { return {
signDirect: tx.signDirect, signDirect: tx.signDirect,
legacyAmino: tx.legacyAmino, legacyAmino: tx.legacyAmino,
eipToSign, eipToSign
} };
} };

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -4,7 +4,7 @@ import {
signatureToWeb3Extension, signatureToWeb3Extension,
Chain, Chain,
Sender Sender
} from '@tharsis/transactions' } from '@tharsis/transactions';
import { Account } from './account'; import { Account } from './account';
@ -18,8 +18,8 @@ export const createTransaction = (message: any, account: Account, sender: Sender
// Sign transaction. // Sign transaction.
const signature = account.sign(message); const signature = account.sign(message);
let extension = signatureToWeb3Extension(chain, sender, signature) let extension = signatureToWeb3Extension(chain, sender, signature);
// Create the txRaw. // 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. * Record.
*/ */
export class Record { export class Record {
_record: any _record: any;
/** /**
* New Record. * New Record.
*/ */
constructor(record: any) { constructor (record: any) {
assert(record); assert(record);
const validator = new Validator(); const validator = new Validator();
@ -26,29 +26,29 @@ export class Record {
this._record = record; this._record = record;
} }
get attributes() { get attributes () {
return Buffer.from(JSON.stringify(this._record), 'binary') return Buffer.from(JSON.stringify(this._record), 'binary');
} }
/** /**
* Serialize record. * Serialize record.
*/ */
serialize() { serialize () {
return { return {
'id': '_', id: '_',
'bond_id': '_', bond_id: '_',
'create_time': '_', create_time: '_',
'expiry_time': '_', expiry_time: '_',
// Setting deleted as false (zero value) throws error in EIP712 signature verification. // Setting deleted as false (zero value) throws error in EIP712 signature verification.
'deleted': true, deleted: true,
'attributes': this.attributes, attributes: this.attributes
} };
} }
/** /**
* Get message to calculate record signature. * Get message to calculate record signature.
*/ */
getMessageToSign() { getMessageToSign () {
return Util.sortJSON(this._record); return Util.sortJSON(this._record);
} }
} }
@ -57,13 +57,13 @@ export class Record {
* Record Signature. * Record Signature.
*/ */
export class Signature { export class Signature {
_pubKey: string _pubKey: string;
_sig: string _sig: string;
/** /**
* New Signature. * New Signature.
*/ */
constructor(pubKey: string, sig: string) { constructor (pubKey: string, sig: string) {
assert(pubKey); assert(pubKey);
assert(sig); assert(sig);
@ -74,10 +74,10 @@ export class Signature {
/** /**
* Serialize Signature. * Serialize Signature.
*/ */
serialize() { serialize () {
return Util.sortJSON({ return Util.sortJSON({
'pub_key': this._pubKey, pub_key: this._pubKey,
'sig': this._sig sig: this._sig
}); });
} }
} }
@ -86,31 +86,31 @@ export class Signature {
* Message Payload. * Message Payload.
*/ */
export class Payload { export class Payload {
_record: Record _record: Record;
_signatures: Signature[] _signatures: Signature[];
/** /**
* New Payload. * New Payload.
*/ */
constructor(record: Record, ...signatures: Signature[]) { constructor (record: Record, ...signatures: Signature[]) {
assert(record); assert(record);
this._record = record; this._record = record;
this._signatures = signatures; this._signatures = signatures;
} }
get record() { get record () {
return this._record; return this._record;
} }
get signatures() { get signatures () {
return this._signatures; return this._signatures;
} }
/** /**
* Add message signature to payload. * Add message signature to payload.
*/ */
addSignature(signature: any) { addSignature (signature: any) {
assert(signature); assert(signature);
this._signatures.push(signature); this._signatures.push(signature);
@ -119,12 +119,12 @@ export class Payload {
/** /**
* Serialize Payload. * Serialize Payload.
*/ */
serialize() { serialize () {
// return Util.sortJSON({ // return Util.sortJSON({
// }); // });
return { return {
'record': this._record.serialize(), record: this._record.serialize(),
'signatures': this._signatures.map(s => s.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 { import {
MsgCreateBond, MsgCreateBond,
@ -9,17 +9,16 @@ import {
MsgRefillBondResponse, MsgRefillBondResponse,
MsgWithdrawBondResponse, MsgWithdrawBondResponse,
MsgCancelBondResponse MsgCancelBondResponse
} from "../../../proto2/cerc/bond/v1/tx"; } 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 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]> = [ export const bondTypes: ReadonlyArray<[string, GeneratedType]> = [
[typeUrlMsgCreateBond, MsgCreateBond], [typeUrlMsgCreateBond, MsgCreateBond],
@ -29,25 +28,25 @@ export const bondTypes: ReadonlyArray<[string, GeneratedType]> = [
[typeUrlMsgWithdrawBond, MsgWithdrawBond], [typeUrlMsgWithdrawBond, MsgWithdrawBond],
[typeUrlMsgWithdrawBondResponse, MsgWithdrawBondResponse], [typeUrlMsgWithdrawBondResponse, MsgWithdrawBondResponse],
[typeUrlMsgCancelBond, MsgCancelBond], [typeUrlMsgCancelBond, MsgCancelBond],
[typeUrlMsgCancelBondResponse, MsgCancelBondResponse], [typeUrlMsgCancelBondResponse, MsgCancelBondResponse]
]; ];
export interface MsgCreateBondEncodeObject extends EncodeObject { export interface MsgCreateBondEncodeObject extends EncodeObject {
readonly typeUrl: "/cerc.bond.v1.MsgCreateBond"; readonly typeUrl: '/cerc.bond.v1.MsgCreateBond';
readonly value: Partial<MsgCreateBond>; readonly value: Partial<MsgCreateBond>;
} }
export interface MsgRefillBondEncodeObject extends EncodeObject { export interface MsgRefillBondEncodeObject extends EncodeObject {
readonly typeUrl: "/cerc.bond.v1.MsgRefillBond"; readonly typeUrl: '/cerc.bond.v1.MsgRefillBond';
readonly value: Partial<MsgRefillBond>; readonly value: Partial<MsgRefillBond>;
} }
export interface MsgWithdrawBondEncodeObject extends EncodeObject { export interface MsgWithdrawBondEncodeObject extends EncodeObject {
readonly typeUrl: "/cerc.bond.v1.MsgWithdrawBond"; readonly typeUrl: '/cerc.bond.v1.MsgWithdrawBond';
readonly value: Partial<MsgWithdrawBond>; readonly value: Partial<MsgWithdrawBond>;
} }
export interface MsgCancelBondEncodeObject extends EncodeObject { export interface MsgCancelBondEncodeObject extends EncodeObject {
readonly typeUrl: "/cerc.bond.v1.MsgCancelBond"; readonly typeUrl: '/cerc.bond.v1.MsgCancelBond';
readonly value: Partial<MsgCancelBond>; readonly value: Partial<MsgCancelBond>;
} }

View File

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

View File

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

1352
yarn.lock

File diff suppressed because it is too large Load Diff