Skip to content
New issue

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

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

Already on GitHub? Sign in to your account

refactor(AENS): refactor claim #709

Merged
merged 10 commits into from
Oct 10, 2019
22 changes: 11 additions & 11 deletions es/ae/aens.js
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@

import * as R from 'ramda'
import { encodeBase58Check, salt } from '../utils/crypto'
import { commitmentHash, prelimaCommitmentHash, isNameValid, getMinimumNameFee } from '../tx/builder/helpers'
import { commitmentHash, isNameValid, getMinimumNameFee } from '../tx/builder/helpers'
import Ae from './'
import { CLIENT_TTL, NAME_FEE, NAME_TTL } from '../tx/builder/schema'

Expand Down Expand Up @@ -169,6 +169,12 @@ async function query (name, opt = {}) {
* @return {Promise<Object>} the result of the claim
*/
async function claim (name, salt, options = {}) {
// Todo remove cross compatibility
const { version } = this.getNodeInfo()
const [majorVersion] = version.split('.')
const vsn = +majorVersion === 5 && version !== '5.0.0-rc.1' ? 2 : 1
options.vsn = options.vsn || vsn

isNameValid(name)
const opt = R.merge(this.Ae.defaults, options)

Expand All @@ -187,7 +193,8 @@ async function claim (name, salt, options = {}) {
}))

const result = await this.send(claimTx, opt)
if (opt.vsn === 1) {
if (opt.vsn === 1 || name.length - 4 > 12) {
delete opt.vsn
const nameInter = this.Chain.defaults.waitMined ? await this.aensQuery(name, opt) : {}
return Object.assign(result, nameInter)
}
Expand All @@ -204,18 +211,11 @@ async function claim (name, salt, options = {}) {
* @return {Promise<Object>}
*/
async function preclaim (name, options = {}) {
// TODO remove cross compatibility
const { version } = this.getNodeInfo()
const [majorVersion] = version.split('.')
const vsn = +majorVersion === 5 && version !== '5.0.0-rc.1' ? 2 : 1

isNameValid(name)
const opt = R.merge(this.Ae.defaults, options)
const _salt = salt()
const height = await this.height()
const hash = vsn === 1
? await prelimaCommitmentHash(name, _salt)
: await commitmentHash(name, _salt)
const hash = commitmentHash(name, _salt)

const preclaimTx = await this.namePreclaimTx(R.merge(opt, {
accountId: await this.address(opt),
Expand All @@ -227,7 +227,7 @@ async function preclaim (name, options = {}) {
return Object.freeze({
...result,
height,
claim: options => this.aensClaim(name, _salt, { ...options, onAccount: opt.onAccount, vsn }),
claim: options => this.aensClaim(name, _salt, { ...options, onAccount: opt.onAccount }),
salt: _salt,
commitmentId: hash
})
Expand Down
10 changes: 6 additions & 4 deletions es/ae/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ import TxBuilder from '../tx/builder'
import * as R from 'ramda'
import { BigNumber } from 'bignumber.js'
import { isAddressValid } from '../utils/crypto'
import { isNameValid } from '../tx/builder/helpers'
import { isNameValid, produceNameId } from '../tx/builder/helpers'

/**
* Sign and post a transaction to the chain
Expand Down Expand Up @@ -84,10 +84,12 @@ async function spend (amount, recipientId, options = {}) {
async function resolveRecipientName (nameOrAddress, { verify = false }) {
if (isAddressValid(nameOrAddress)) return nameOrAddress
if (isNameValid(nameOrAddress)) {
const { id, pointers } = await this.getName(nameOrAddress)
// Validation
if (verify && !pointers.find(({ id }) => id.split('_')[0] === 'ak')) throw new Error(`Name ${nameOrAddress} do not have pointers for account`)
return id
if (verify) {
const { pointers } = await this.getName(nameOrAddress)
if (!pointers.find(({ id }) => id.split('_')[0] === 'ak')) throw new Error(`Name ${nameOrAddress} do not have pointers for account`)
}
return produceNameId(nameOrAddress)
}
}

Expand Down
30 changes: 15 additions & 15 deletions es/tx/builder/helpers.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import {
decodeBase64Check,
encodeBase58Check, encodeBase64Check,
hash,
nameId,
nameId as nameHash,
salt
} from '../../utils/crypto'
import { toBytes } from '../../utils/bytes'
Expand Down Expand Up @@ -89,19 +89,16 @@ export function formatSalt (salt) {
}

/**
* Generate the commitment hash by hashing the formatted salt and
* name, base 58 encoding the result and prepending 'cm_'
*
* Encode a domain name
* @function
* @alias module:@aeternity/aepp-sdk/es/tx/builder/helpers
* @function prelimaCommitmentHash
* @category async
* @rtype (name: String, salt?: String) => hash: Promise[String]
* @param {String} name - Name to be registered
* @param {Number} salt Random salt
* @return {String} Commitment hash
* @param {String} name Name to encode
* @return {String} `nm_` prefixed encoded domain name
*/
export async function prelimaCommitmentHash (name, salt = createSalt()) {
return `cm_${encodeBase58Check(hash(Buffer.concat([nameId(name.toLowerCase()), formatSalt(salt)])))}`
export function produceNameId (name) {
const namespace = R.last(name.split('.'))
if (namespace === 'aet') return encode(hash(name.toLowerCase()), 'nm')
return encode(nameHash(name), 'nm')
}

/**
Expand All @@ -116,8 +113,10 @@ export async function prelimaCommitmentHash (name, salt = createSalt()) {
* @param {Number} salt Random salt
* @return {String} Commitment hash
*/
export async function commitmentHash (name, salt = createSalt()) {
return `cm_${encodeBase58Check(hash(Buffer.concat([Buffer.from(name), formatSalt(salt)])))}`
export function commitmentHash (name, salt = createSalt()) {
const namespace = R.last(name.split('.'))
if (namespace === 'aet') return `cm_${encodeBase58Check(hash(Buffer.concat([Buffer.from(name), formatSalt(salt)])))}`
return `cm_${encodeBase58Check(hash(Buffer.concat([nameHash(name.toLowerCase()), formatSalt(salt)])))}`
}

/**
Expand Down Expand Up @@ -293,5 +292,6 @@ export default {
oracleQueryId,
createSalt,
buildHash,
isNameValid
isNameValid,
produceNameId
}
4 changes: 3 additions & 1 deletion es/tx/builder/schema.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,12 @@ import BigNumber from 'bignumber.js'
export const VSN = 1
export const VSN_2 = 2

// # TRANSACTION DEFAULT TTL
export const TX_TTL = 0

// # AENS
export const AENS_NAME_DOMAINS = ['aet', 'test']
export const NAME_TTL = 500
// # Aens
// # max number of block into the future that the name is going to be available
// # https://github.com/aeternity/protocol/blob/epoch-v0.22.0/AENS.md#update
// # https://github.com/aeternity/protocol/blob/44a93d3aab957ca820183c3520b9daf6b0fedff4/AENS.md#aens-entry
Expand Down
4 changes: 2 additions & 2 deletions es/tx/tx.js
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ import ChainNode from '../chain/node'
import Tx from './'

import { buildTx, calculateFee } from './builder'
import { ABI_VERSIONS, MIN_GAS_PRICE, PROTOCOL_VM_ABI, TX_TYPE, VM_TYPE } from './builder/schema'
import { ABI_VERSIONS, MIN_GAS_PRICE, PROTOCOL_VM_ABI, TX_TYPE, VM_TYPE, TX_TTL } from './builder/schema'
import { buildContractId, oracleQueryId } from './builder/helpers'

async function spendTx ({ senderId, recipientId, amount, payload = '' }) {
Expand Down Expand Up @@ -392,7 +392,7 @@ function getVmVersion (txType, { vmVersion, abiVersion, backend } = {}) {
* @param {boolean} relative ttl is absolute or relative(default: true(relative))
* @return {number} Absolute Ttl
*/
async function calculateTtl (ttl = 0, relative = true) {
async function calculateTtl (ttl = TX_TTL, relative = true) {
if (ttl === 0) return 0
if (ttl < 0) throw new Error('ttl must be greater than 0')

Expand Down
5 changes: 3 additions & 2 deletions es/utils/crypto.js
Original file line number Diff line number Diff line change
Expand Up @@ -70,12 +70,13 @@ export function formatAddress (format = ADDRESS_FORMAT.api, address) {
* Check if address is valid
* @rtype (input: String) => valid: Boolean
* @param {String} address - Address
* @param {String} prefix Transaction prefix. Default: 'ak'
* @return {Boolean} valid
*/
export function isAddressValid (address) {
export function isAddressValid (address, prefix = 'ak') {
let isValid
try {
isValid = decodeBase58Check(assertedType(address, 'ak')).length === 32
isValid = decodeBase58Check(assertedType(address, prefix)).length === 32
} catch (e) {
isValid = false
}
Expand Down