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

WIP: Fabo/133 bond hookup #258

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
68 changes: 0 additions & 68 deletions app/src/main/mockServer.js
Original file line number Diff line number Diff line change
Expand Up @@ -28,74 +28,6 @@ module.exports = function (port = 8999) {
// next()
// })

// delegation mock API
app.post('/tx/stake/delegate/:pubkey/:amount', (req, res) => {
res.json({
'type': 'sigs/one',
'data': {
'tx': {
'type': 'chain/tx',
'data': {
'chain_id': 'gaia-1',
'expires_at': 0,
'tx': {
'type': 'nonce',
'data': {
'sequence': 1,
'signers': [
{
'chain': '',
'app': 'sigs',
'addr': '84A057DCE7E1DB8EBE3903FC6B2D912E63EF9BEA'
}
],
'tx': {
'type': 'coin/send',
'data': {
'inputs': [
{
'address': {
'chain': '',
'app': 'sigs',
'addr': '84A057DCE7E1DB8EBE3903FC6B2D912E63EF9BEA'
},
'coins': [
{
'denom': 'atom',
'amount': 1
}
]
}
],
'outputs': [
{
'address': {
'chain': '',
'app': 'sigs',
'addr': '84A057DCE7E1DB8EBE3903FC6B2D912E63EF9BEA'
},
'coins': [
{
'denom': 'atom',
'amount': 1
}
]
}
]
}
}
}
}
}
},
'signature': {
'Sig': null,
'Pubkey': null
}
}
})
})

// tx history
app.get('/tx/bondings/delegator/:address', (req, res) => {
let { address } = req.params
Expand Down
4 changes: 2 additions & 2 deletions app/src/renderer/components/common/NiSessionSignIn.vue
Original file line number Diff line number Diff line change
Expand Up @@ -68,8 +68,8 @@ export default {
...mapGetters(['user']),
accounts () {
let accounts = this.user.accounts
accounts = accounts.filter((name) => name !== 'trunk')
return accounts.map((name) => ({ key: name, value: name }))
accounts = accounts.filter(({name}) => name !== 'trunk')
return accounts.map(({name}) => ({ key: name, value: name }))
}
},
mounted () {
Expand Down
38 changes: 28 additions & 10 deletions app/src/renderer/components/staking/PageBond.vue
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ page.page-bond(title="Bond Atoms")
form-struct(:submit="onSubmit")
form-group(v-for='(delegate, index) in fields.delegates' key='delegate.id'
:error="$v.fields.delegates.$each[index].$error")
Label {{ delegate.delegate.keybaseID }} ({{ percentAtoms(delegate.atoms) }})
Label {{ shortenLabel(delegate.delegate.id, 20) }} ({{ percentAtoms(delegate.atoms) }})
field-group
field(
type="number"
Expand Down Expand Up @@ -67,8 +67,11 @@ export default {
},
computed: {
...mapGetters(['shoppingCart', 'user']),
reservedAtoms () {
return this.shoppingCart.reduce((sum, d) => sum + (d.reservedAtoms || 0), 0)
},
unreservedAtoms () {
return this.user.atoms - this.fields.reservedAtoms
return this.user.atoms - this.reservedAtoms
},
unbondedAtoms () {
let value = this.unreservedAtoms
Expand Down Expand Up @@ -153,14 +156,23 @@ export default {
this.$v.$touch()
if (!this.$v.$error) {
this.$store.commit('activateDelegation')
try {
await this.$store.dispatch('submitDelegation', this.fields)
this.$store.commit('notify', { title: 'Atoms Bonded',
body: 'You have successfully bonded your atoms. You can rebond after the 30 day unbonding period.' })
} catch (err) {
this.$store.commit('notifyError', { title: 'Error While Bonding Atoms',
body: err.message })
}
await Promise.all(this.fields.delegates.map(async delegation => {
try {
await this.$store.dispatch('submitDelegation', {
value: delegation.atoms,
candidate: delegation.delegate,
userAddress: this.user.address,
account: this.user.account,
password: this.user.password
})
this.$store.commit('notify', { title: 'Atoms Bonded',
body: `You have successfully bonded ${delegation.atoms} atoms to ${delegation.delegate.id}. You can rebond after the 30 day unbonding period.` })
} catch (err) {
this.$store.commit('notifyError', { title: `Error While Bonding Atoms to ${delegation.delegate.id}`,
body: err.message })
}
}))
this.$router.push('/staking')
}
},
resetAlloc () {
Expand All @@ -182,6 +194,12 @@ export default {
this.$store.commit('removeFromCart', delegateId)
this.resetAlloc()
}
},
shortenLabel (label, maxLength) {
if (label.length <= maxLength) {
return label
}
return label.substr(0, maxLength - 3) + '...'
}
},
mounted () {
Expand Down
13 changes: 11 additions & 2 deletions app/src/renderer/components/staking/PageDelegates.vue
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,8 @@ export default {
ToolBar
},
computed: {
...mapGetters(['delegates', 'filters', 'shoppingCart', 'config']),
...mapGetters(['delegates', 'filters', 'shoppingCart', 'config', 'user']),
address () { return this.user.address },
pageTitle () {
if (this.shoppingCart.length > 0) {
return `Delegates (${this.shoppingCart.length} Selected)`
Expand Down Expand Up @@ -78,8 +79,16 @@ export default {
]
}
}),
watch: {
address: function (address) {
address && this.updateDelegates(address)
}
},
methods: {
updateDelegates () { this.$store.dispatch('getDelegates') },
async updateDelegates (address) {
let candidates = await this.$store.dispatch('getDelegates')
this.$store.dispatch('getBondedDelegates', {candidates, address})
},
setSearch (bool) { this.$store.commit('setSearchVisible', ['delegates', bool]) }
},
mounted () {
Expand Down
14 changes: 8 additions & 6 deletions app/src/renderer/vuex/modules/delegates.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,10 @@ export default ({ dispatch, node }) => {

// return if we already have this delegate
for (let existingDelegate of state) {
if (existingDelegate.id === delegate.id) return
if (existingDelegate.id === delegate.id) {
Object.assign(existingDelegate, delegate)
return
}
}

state.push(delegate)
Expand All @@ -20,19 +23,18 @@ export default ({ dispatch, node }) => {
const actions = {
async getDelegates ({ dispatch }) {
let delegatePubkeys = (await node.candidates()).data
for (let pubkey of delegatePubkeys) {
dispatch('getDelegate', pubkey)
}
return Promise.all(delegatePubkeys.map(pubkey => {
return dispatch('getDelegate', pubkey)
}))
},
async getDelegate ({ commit }, pubkey) {
let delegate = (await axios.get('http://localhost:8998/query/stake/candidate/' + pubkey.data)).data.data
// TODO move into cosmos-sdk
// let delegate = (await node.candidate(pubkeyToString(pubkey))).data
commit('addDelegate', delegate)
return delegate
}
}

setTimeout(() => dispatch('getDelegates'), 1000)

return { state, mutations, actions }
}
39 changes: 39 additions & 0 deletions app/src/renderer/vuex/modules/delegation.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import axios from 'axios'

export default ({ dispatch, node }) => {
const actions = {
async submitDelegation ({state, commit}, {
value,
candidate,
userAddress,
account,
password
}) {
let tx = (await axios.post('http://localhost:8998/build/stake/delegate', {
'from': {
'app': 'Cosmos',
'addr': userAddress
},
'pub_key': candidate.pub_key,
'sequence': 1,
'amount': {
'denom': 'fermion',
'amount': value
}
})).data
// TODO move to cosmos-sdk
// let tx = await node.buildDelegate([ delegate.id, delegate.atoms ])
let signedTx = await node.sign({
name: account,
password,
tx
})
let res = await node.postTx(signedTx)
if (res.check_tx.gas === '0') {
throw new Error(`Delegating to ${candidate.pub_key.data} failed: ${res.check_tx.log}`)
}
}
}

return { actions }
}
3 changes: 2 additions & 1 deletion app/src/renderer/vuex/modules/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,5 +8,6 @@ export default (opts) => ({
shoppingCart: require('./shoppingCart.js').default(opts),
user: require('./user.js').default(opts),
validators: require('./validators.js').default(opts),
wallet: require('./wallet.js').default(opts)
wallet: require('./wallet.js').default(opts),
delegation: require('./delegation.js').default(opts)
})
27 changes: 25 additions & 2 deletions app/src/renderer/vuex/modules/shoppingCart.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
export default ({ commit, basecoin }) => {
import axios from 'axios'

export default ({ commit }) => {
let state = { delegates: [] }

const mutations = {
Expand All @@ -11,8 +13,29 @@ export default ({ commit, basecoin }) => {
},
removeFromCart (state, delegate) {
state.delegates = state.delegates.filter(c => c.id !== delegate)
},
reserveAtoms (state, {delegateId, value}) {
state.delegates.find(d => d.id === delegateId).reservedAtoms = value
},
setShares (state, {candidateId, value}) {
state.delegates.find(c => c.id === candidateId).atoms = value
}
}

let actions = {
async getBondedDelegates ({ state, dispatch }, {candidates, address}) {
// TODO move into cosmos-sdk
candidates.forEach(candidate => {
commit('addToCart', candidate)
dispatch('getBondedDelegate', {address, pubkey: candidate.pub_key.data})
})
},
async getBondedDelegate ({ commit }, {address, pubkey}) {
// TODO move into cosmos-sdk
let bond = (await axios.get('http://localhost:8998/query/stake/delegator/' + address + '/' + pubkey)).data.data
commit('setShares', {candidateId: bond.PubKey.data, value: bond.Shares})
}
}

return { state, mutations }
return { state, mutations, actions }
}
47 changes: 7 additions & 40 deletions app/src/renderer/vuex/modules/user.js
Original file line number Diff line number Diff line change
@@ -1,29 +1,13 @@
export default ({ commit, node }) => {
const emptyNomination = {
keybase: '',
country: '',
website: '',
startDate: '',
commission: '',
serverDetails: '',
description: '',
ownCoinsBonded: ''
}

const emptyUser = {
const state = {
atoms: 2097152,
nominationActive: false,
nomination: JSON.parse(JSON.stringify(emptyNomination)),
delegationActive: false,
delegation: [],
pubkey: '',
privkey: null,
signedIn: false,
accounts: []
accounts: [],
password: null,
account: null,
address: null
}

const state = JSON.parse(JSON.stringify(emptyUser))

const mutations = {
activateDelegation (state) {
state.delegationActive = true
Expand All @@ -44,7 +28,7 @@ export default ({ commit, node }) => {
async loadAccounts ({ commit }) {
try {
let keys = await node.listKeys()
commit('setAccounts', keys.map((key) => key.name))
commit('setAccounts', keys)
} catch (err) {
commit('notifyError', { title: `Couldn't read keys`, body: err.message })
}
Expand Down Expand Up @@ -101,6 +85,7 @@ export default ({ commit, node }) => {
async signIn ({ state, dispatch }, { password, account }) {
state.password = password
state.account = account
state.address = state.accounts.find(_account => _account.name === account).address
state.signedIn = true

let key = await node.getKey(account)
Expand All @@ -113,24 +98,6 @@ export default ({ commit, node }) => {

commit('setModalSession', true)
dispatch('showInitialScreen')
},
async submitDelegation (state, value) {
state.delegation = value
console.log('submitting delegation txs: ', JSON.stringify(state.delegation))

for (let delegate of value.delegates) {
let tx = await node.buildDelegate([ delegate.id, delegate.atoms ])
// TODO: use wallet key management
let signedTx = await node.sign({
name: state.name,
password: state.default,
tx
})
let res = await node.postTx(signedTx)
console.log(res)
}

commit('activateDelegation', true)
}
}

Expand Down