Skip to content

Commit

Permalink
wip: balance system, contract ownership of hive, contract env
Browse files Browse the repository at this point in the history
  • Loading branch information
vaultec81 committed Apr 2, 2024
1 parent 5f47edb commit 1c115f1
Show file tree
Hide file tree
Showing 12 changed files with 666 additions and 143 deletions.
24 changes: 22 additions & 2 deletions src/modules/api/graphql/schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,8 @@ export const schema = `
interface DepositDrain {
deposit_id: String
amount: Float
token: String
owner: String
}
interface BlockRef {
block_ref: String
Expand All @@ -125,6 +127,17 @@ export const schema = `
contract_id: String
controllers_hash: String
}
type GetBalanceTokens {
HBD: Float
HIVE: Float
}
type GetBalanceResult {
account: String
block_height: Int
tokens: GetBalanceTokens
}
type FindtransactionResult {
txs: [Transaction]
}
Expand All @@ -140,11 +153,18 @@ export const schema = `
type Query {
contractState(id: String): ContractState
findTransaction(filterOptions: FindTransactionFilter, decodedFilter: JSON): FindtransactionResult
findContract(id: String): FindContractResult
findCID(id: String): findCIDResult
findDeposit(id: String): Deposit
findLedgerTXs(byContractId: String, byToFrom: String): FindtransactionResult
getAccountBalance(account: String): GetBalanceResult
# Need Revision
findContract(id: String): FindContractResult
findCID(id: String): findCIDResult
# End Need Revision
submitTransactionV1(tx: String!, sig: String!): TransactionSubmitResult
getAccountNonce(keyGroup: [String]!): AccountNonceResult
Expand Down
99 changes: 58 additions & 41 deletions src/services/new/chainBridgeV2.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,42 +13,22 @@ import { EventRecord, ParserFuncArgs, StreamParser, computeKeyId } from './utils
import { CID } from 'multiformats';




interface ProcessingDepthMap {
hive_block_parser: number
vsc_block_parser: number
vsc_block_verification: number
}







/**
* Tracks account metadata
*
*/
export class AccountTracer {

async txTick() {

}

async trace(args: {

}) {

interface BlockHeaderDbRecord {
id: string
proposer: string
merkle_root: string
sig_root: string
block: string
start_block: number
end_block: number
slot_height: number
stats: {
size: number
}
ts: Date
}






export class ChainBridgeV2 {
streamParser: StreamParser
db: Db;
Expand All @@ -59,7 +39,7 @@ export class ChainBridgeV2 {
witnessHistoryDb: Collection
consensusDb: Collection
consensusDataDb: Collection
blockHeaders: Collection<BlockHeader>
blockHeaders: Collection<BlockHeaderDbRecord>
contractOutputDb: Collection
pinQueue: PQueue;
self: NewCoreService;
Expand Down Expand Up @@ -121,7 +101,7 @@ export class ChainBridgeV2 {
protected async blockParser(args: ParserFuncArgs) {
const {data, halt} = args;

const {tx, blkHeight} = data;
const {tx, blkHeight, block_id, timestamp} = data;

for(let [op, opPayload] of tx.operations) {

Expand Down Expand Up @@ -363,7 +343,7 @@ export class ChainBridgeV2 {
console.log('Not hitting vote majority')
throw new Error('Not hitting vote majority')
}
const blockId = (await this.self.ipfs.dag.put(json.signed_block, {
const anchorId = (await this.self.ipfs.dag.put(json.signed_block, {
onlyHash: true
})).toString()

Expand All @@ -375,7 +355,7 @@ export class ChainBridgeV2 {
slot_height: slotHeight
},
{
id: blockId
id: anchorId
}
]
})
Expand All @@ -389,7 +369,7 @@ export class ChainBridgeV2 {
console.log('full block content', block_full)

await this.blockHeaders.findOneAndUpdate({
id: blockId
id: anchorId
}, {
$set: {
proposer: opPayload.required_auths[0],
Expand All @@ -401,7 +381,8 @@ export class ChainBridgeV2 {
slot_height: slotHeight,
stats: {
size: (await this.self.ipfs.block.get(signed_block.block)).length
}
},
ts: timestamp
}
}, {
upsert: true
Expand All @@ -426,7 +407,8 @@ export class ChainBridgeV2 {
}, {
$set: {
anchored_height: blkHeight,
anchored_block: blockId,
anchored_id: anchorId,
anchored_block: block_id,
contract_id: txData.contract_id,
state_merkle: txData.state_merkle,
//TODO: look into properly handling side effects aka on chain actions
Expand Down Expand Up @@ -462,6 +444,39 @@ export class ChainBridgeV2 {
}
})
}
if(txData.ledger_results) {
for(let idx in txData.ledger_results) {
const ledgerEntry = txData.ledger_results[idx]
if(ledgerEntry.to === "#withdraw") {
//Safety for when replaying
const withdrawRecord = await this.self.witness.balanceKeeper.withdrawDb.findOne({
id: `${tx.id}-${idx}`
})
if(!withdrawRecord) {
await this.self.witness.balanceKeeper.withdrawDb.insertOne({
id: `${tx.id}-${idx}`,
amount: ledgerEntry.amount,
from: ledgerEntry.from,
dest: ledgerEntry.dest,
type: "CONTRACT_WITHDRAW"
})
}
}
await this.self.witness.balanceKeeper.ledgerDb.findOneAndUpdate({
id: `${tx.id}-${idx}`
}, {
$set: {
amount: ledgerEntry.amount,
from: ledgerEntry.from,
to: ledgerEntry.to,
dest: ledgerEntry.dest,
owner: ledgerEntry.owner,
}
}, {
upsert: true
})
}
}
} else if(tx.type === TransactionDbType.input) {

const txRecord = await this.self.transactionPool.txDb.findOne({
Expand All @@ -478,7 +493,8 @@ export class ChainBridgeV2 {
$set: {
status: TransactionDbStatus.included,
anchored_height: endBlock,
anchored_block: blockId,
anchored_block: block_id,
anchored_id: anchorId,
}
})
} else {
Expand All @@ -497,7 +513,8 @@ export class ChainBridgeV2 {
accessible: true,
first_seen: new Date(),
anchored_height: endBlock,
anchored_block: blockId,
anchored_block: block_id,
anchored_id: block_id, //Same for Hive
src: "vsc"
})
}
Expand Down
43 changes: 38 additions & 5 deletions src/services/new/contractEngineV2.ts
Original file line number Diff line number Diff line change
Expand Up @@ -68,11 +68,17 @@ class VmContext {
throw new Error('Contract ID not registered with VmContext')
}

console.log(tx)



const callOutput = await this.vm.call({
contract_id,
action: tx.data.action,
payload: JSON.stringify(tx.data.payload)
payload: JSON.stringify(tx.data.payload),
env: {

} as any
})

return callOutput
Expand Down Expand Up @@ -175,10 +181,36 @@ export class ContractEngineV2 {
const txResults = []

for(let tx of args.txs) {
const blockHeader = await this.self.chainBridge.blockHeaders.findOne({
id: tx.anchored_id
})
const requiredAuths = tx.required_auths.map(e => e.value).map(e => {
if(tx.src === 'hive') {
//Format should be human readable
return `hive:${e}`
} else {
//i.e did:key:123etcetc
return e
}
})
const result = await vm.call({
contract_id: args.contract_id,
action: tx.data.action,
payload: JSON.stringify(tx.data.payload)
payload: JSON.stringify(tx.data.payload),
env: {
'anchor.id': tx.anchored_id,
'anchor.height': tx.anchored_height,
'anchor.block': tx.anchored_block,
'anchor.timestamp': blockHeader.ts.getTime(),


'msg.sender': requiredAuths[0],
//Retain the type info as well.
//TODO: properly parse and provide authority type to contract
//Such as ACTIVE vs POSTING auth
'msg.required_auths': tx.required_auths,
'tx.origin': requiredAuths[0],
} as any
})


Expand All @@ -204,13 +236,14 @@ export class ContractEngineV2 {
...(result.IOGas > 0 ? {gas: result.IOGas} : {})
})
}
const state_merkle = await vm.finishAndCleanup()
const {stateMerkle, ledgerResults} = await vm.finishAndCleanup()
console.log('finishing and cleaning up')

const returnObj = {
input_map: args.txs.map(e => e.id),
state_merkle,
results: txResults
state_merkle: stateMerkle,
results: txResults,
ledger_results: ledgerResults
}

console.log('returnObj', returnObj)
Expand Down
6 changes: 4 additions & 2 deletions src/services/new/p2pService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -137,12 +137,13 @@ export class PeerChannel {
let drain = pushable()
let sink = pushable()
void (async () => {
const events = this.events.on('message', (message) => {
const func = (message) => {
//TODO make this feed the handler
if(json_payload.req_id === message.req_id) {
sink.push(message.payload)
}
})
}
this.events.on('message', func)
// this.logger.debug('peer events', events)
for await (let item of drain) {
this.logger.debug('Channel Response', item)
Expand All @@ -157,6 +158,7 @@ export class PeerChannel {
req_id: json_payload.req_id,
flags: ['end']
})
this.events.removeListener('message', func)
})()
this._handles[json_payload.type].handler({from: msg.from.toString(), message: json_payload.payload, drain, sink})
}
Expand Down
23 changes: 22 additions & 1 deletion src/services/new/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -186,6 +186,9 @@ export interface TransactionDbRecordV2 {
accessible: boolean
first_seen: Date
src: 'vsc' | 'hive'
//ID of anchor record
anchored_id?: string
//Full block ID of Hive block including anchor record
anchored_block?: string
anchored_height?: number
//Witness data
Expand Down Expand Up @@ -251,4 +254,22 @@ export interface AccountNonceDbRecord {
id: string
nonce: number
key_group?: string
}
}



interface LedgerIn {
amount: number
from: string
owner: string
unit: "HBD" | "HIVE"
dest?: string
}
interface LedgerOut {
amount: number
owner: string
to: string
unit: "HBD" | "HIVE"
dest?: string
}
export type LedgerType = LedgerIn | LedgerOut
7 changes: 5 additions & 2 deletions src/services/new/utils/streamUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -115,13 +115,13 @@ export class StreamParser {
}
}


await this.events.updateOne({
id: 'hive_block',
key: block_height
}, {
$set: {
block_id: block.block_id,
timestamp: new Date(block.timestamp + 'Z'),
transactions
}
}, {
Expand Down Expand Up @@ -236,7 +236,10 @@ export class StreamParser {
type: 'tx',
data: {
tx,
blkHeight: Number(blk.key)
//Fix: to underscore case.
blkHeight: Number(blk.key),
block_id: blk.block_id,
timestamp: blk.timestamp
},
halt: this.halt
})
Expand Down
Loading

0 comments on commit 1c115f1

Please sign in to comment.