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,15 +33,15 @@ 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.
@ -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);
@ -169,7 +169,7 @@ export class Account {
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);
@ -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,23 +11,22 @@ 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();
@ -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
@ -205,7 +204,7 @@ 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 = 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);
@ -217,7 +216,7 @@ export class Registry {
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.');
@ -248,9 +247,9 @@ export class Registry {
* 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,7 +313,7 @@ export class Registry {
fee fee
); );
return laconicClient.registry.decode(response.msgResponses[0]) return laconicClient.registry.decode(response.msgResponses[0]);
} }
/** /**
@ -325,7 +324,7 @@ 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 = 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);
@ -339,7 +338,7 @@ 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 = 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);
@ -353,7 +352,7 @@ 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 = 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);
@ -367,7 +366,7 @@ 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 = 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);
@ -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);
@ -400,7 +399,7 @@ 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 = 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);
@ -414,7 +413,7 @@ 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 = 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);
@ -428,7 +427,7 @@ 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 = 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);
@ -456,7 +455,7 @@ 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 = 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);
@ -477,7 +476,7 @@ 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 = 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);
@ -524,7 +523,7 @@ 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);
} }
@ -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(
cometClient: Comet38Client,
signer: OfflineSigner,
options: SigningStargateClientOptions,
) {
super(cometClient, signer, options);
}
public async createBond ( 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,7 +51,7 @@ export class LaconicClient extends SigningStargateClient {
amount amount
}) })
] ]
}, }
}; };
return this.signAndBroadcast(signer, [createMsg], fee, memo); return this.signAndBroadcast(signer, [createMsg], fee, memo);
@ -72,8 +62,8 @@ export class LaconicClient extends SigningStargateClient {
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,7 +76,7 @@ export class LaconicClient extends SigningStargateClient {
amount amount
}) })
] ]
}, }
}; };
return this.signAndBroadcast(signer, [createMsg], fee, memo); return this.signAndBroadcast(signer, [createMsg], fee, memo);
@ -97,8 +87,8 @@ export class LaconicClient extends SigningStargateClient {
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,7 +101,7 @@ export class LaconicClient extends SigningStargateClient {
amount amount
}) })
] ]
}, }
}; };
return this.signAndBroadcast(signer, [createMsg], fee, memo); return this.signAndBroadcast(signer, [createMsg], fee, memo);
@ -120,15 +110,15 @@ export class LaconicClient extends SigningStargateClient {
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,9 +27,9 @@ 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,
@ -41,23 +41,23 @@ export function createTxMsgCommitBid(
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 (
@ -65,23 +65,23 @@ export function createTxMsgRevealBid(
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 (
@ -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,14 +107,14 @@ 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,
@ -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
@ -128,23 +128,23 @@ export function createTxMsgCreateBond(
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 (
@ -152,25 +152,25 @@ export function createTxMsgRefillBond(
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 (
@ -178,25 +178,25 @@ export function createTxMsgWithdrawBond(
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 (
@ -204,21 +204,21 @@ export function createTxMsgCancelBond(
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 (
@ -226,23 +226,23 @@ export function createTxMsgAssociateBond(
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 (
@ -250,21 +250,21 @@ export function createTxMsgDissociateBond(
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 (
@ -272,21 +272,21 @@ export function createTxMsgDissociateRecords(
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 (
@ -294,29 +294,29 @@ export function createTxMsgReAssociateRecords(
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,36 +410,36 @@ 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,
@ -450,8 +450,8 @@ function createMsgCancelBond(
value: { value: {
id, id,
signer signer
},
} }
};
} }
const protoCreateMsgCancelBond = ( const protoCreateMsgCancelBond = (
@ -461,13 +461,13 @@ 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,
@ -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,13 +493,13 @@ 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,
@ -510,8 +510,8 @@ function createMsgDissociateBond(
value: { value: {
record_id: recordId, record_id: recordId,
signer signer
},
} }
};
} }
const protoCreateMsgDissociateBond = ( const protoCreateMsgDissociateBond = (
@ -521,13 +521,13 @@ 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,
@ -538,8 +538,8 @@ function createMsgDissociateRecords(
value: { value: {
bond_id: bondId, bond_id: bondId,
signer signer
},
} }
};
} }
const protoCreateMsgDissociateRecords = ( const protoCreateMsgDissociateRecords = (
@ -549,13 +549,13 @@ 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,
@ -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
@ -116,23 +116,23 @@ export function createTxMsgReserveAuthority(
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 (
@ -140,23 +140,23 @@ export function createTxMsgSetName(
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 (
@ -164,23 +164,23 @@ export function createTxMsgSetRecord(
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 (
@ -188,23 +188,23 @@ export function createTxMsgSetAuthorityBond(
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 (
@ -212,21 +212,21 @@ export function createTxMsgDeleteName(
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 (
@ -240,26 +240,26 @@ 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,
@ -272,8 +272,8 @@ function createMsgSetName(
crn, crn,
cid, cid,
signer signer
},
} }
};
} }
const protoCreateMsgSetName = ( const protoCreateMsgSetName = (
@ -284,14 +284,14 @@ 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,
@ -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,30 +313,30 @@ 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,
@ -349,8 +349,8 @@ function createMsgSetAuthorityBond(
name, name,
bond_id: bondId, bond_id: bondId,
signer signer
},
} }
};
} }
const protoCreateMsgSetAuthorityBond = ( const protoCreateMsgSetAuthorityBond = (
@ -361,14 +361,14 @@ 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,
@ -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()}`;
@ -67,21 +67,21 @@ const nameserviceExpiryTests = () => {
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);
@ -90,13 +90,13 @@ const nameserviceExpiryTests = () => {
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,8 +97,8 @@ const auctionFields = `
* Registry * Registry
*/ */
export class RegistryClient { export class RegistryClient {
_restEndpoint: string _restEndpoint: string;
_graph: any _graph: any;
/** /**
* Get query result. * Get query result.
@ -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;
@ -296,7 +296,7 @@ export class RegistryClient {
const result = await this._graph(query)(variables); const result = await this._graph(query)(variables);
return result['lookupAuthorities']; return result.lookupAuthorities;
} }
/** /**
@ -341,7 +341,7 @@ export class RegistryClient {
const result = await this._graph(query)(variables); const result = await this._graph(query)(variables);
return result['lookupNames']; return result.lookupNames;
} }
/** /**
@ -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;
@ -430,7 +430,7 @@ export class RegistryClient {
const { data } = await axios.post( const { data } = await axios.post(
`${this._restEndpoint}${generateEndpointBroadcast()}`, `${this._restEndpoint}${generateEndpointBroadcast()}`,
tx tx
) );
return data; return data;
} }

View File

@ -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,7 +8,7 @@ import { Util } from './util';
* Record. * Record.
*/ */
export class Record { export class Record {
_record: any _record: any;
/** /**
* New Record. * New Record.
@ -27,7 +27,7 @@ export class Record {
} }
get attributes () { get attributes () {
return Buffer.from(JSON.stringify(this._record), 'binary') return Buffer.from(JSON.stringify(this._record), 'binary');
} }
/** /**
@ -35,14 +35,14 @@ export class 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
} };
} }
/** /**
@ -57,8 +57,8 @@ 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.
@ -76,8 +76,8 @@ export class Signature {
*/ */
serialize () { serialize () {
return Util.sortJSON({ return Util.sortJSON({
'pub_key': this._pubKey, pub_key: this._pubKey,
'sig': this._sig sig: this._sig
}); });
} }
} }
@ -86,8 +86,8 @@ 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.
@ -123,8 +123,8 @@ export class Payload {
// 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
@ -54,17 +54,17 @@ export class Util {
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:
@ -106,14 +106,14 @@ 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