Skip to content

Commit

Permalink
add payment rpc (#172)
Browse files Browse the repository at this point in the history
  • Loading branch information
ermalkaleci authored Jan 27, 2023
1 parent c5f772e commit e2d4449
Show file tree
Hide file tree
Showing 13 changed files with 386 additions and 227 deletions.
8 changes: 4 additions & 4 deletions executor/src/task.rs
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ impl RuntimeVersion {
#[serde(rename_all = "camelCase")]
pub struct TaskCall {
wasm: HexString,
calls: Option<Vec<(String, HexString)>>,
calls: Vec<(String, Vec<HexString>)>,
storage: Vec<(HexString, Option<HexString>)>,
mock_signature_host: bool,
allow_unresolved_imports: bool,
Expand Down Expand Up @@ -101,11 +101,11 @@ pub async fn run_task(task: TaskCall, js: crate::JsCallback) -> Result<TaskRespo
.unwrap();
let mut ret: Result<Vec<u8>, String> = Ok(Vec::new());

for (call, params) in task.calls.as_ref().unwrap() {
for (call, params) in task.calls {
let mut vm = runtime_host::run(runtime_host::Config {
virtual_machine: vm_proto.clone(),
function_to_call: call,
parameter: iter::once(params.as_ref()),
function_to_call: call.as_str(),
parameter: params.into_iter().map(|x| x.0),
top_trie_root_calculation_cache: None,
storage_top_trie_changes,
offchain_storage_changes,
Expand Down
20 changes: 10 additions & 10 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -30,14 +30,14 @@
},
"dependencies": {
"@acala-network/chopsticks-executor": "workspace:*",
"@polkadot/api": "^9.11.3",
"@polkadot/rpc-provider": "^9.11.3",
"@polkadot/types": "^9.11.3",
"@polkadot/types-codec": "^9.11.3",
"@polkadot/types-known": "^9.11.3",
"@polkadot/api": "^9.12.1",
"@polkadot/rpc-provider": "^9.12.1",
"@polkadot/types": "^9.12.1",
"@polkadot/types-codec": "^9.12.1",
"@polkadot/types-known": "^9.12.1",
"@polkadot/util": "^10.2.6",
"@polkadot/util-crypto": "^10.2.6",
"axios": "^1.2.3",
"axios": "^1.2.5",
"js-yaml": "^4.1.0",
"jsondiffpatch": "^0.4.1",
"lodash": "^4.17.21",
Expand All @@ -56,9 +56,9 @@
"@types/lodash": "^4.14.191",
"@types/node": "^18.11.18",
"@types/ws": "^8.5.4",
"@types/yargs": "^17.0.19",
"@typescript-eslint/eslint-plugin": "^5.48.2",
"@typescript-eslint/parser": "^5.48.2",
"@types/yargs": "^17.0.20",
"@typescript-eslint/eslint-plugin": "^5.49.0",
"@typescript-eslint/parser": "^5.49.0",
"eslint": "^8.32.0",
"eslint-config-prettier": "^8.6.0",
"eslint-plugin-import": "^2.27.5",
Expand All @@ -68,7 +68,7 @@
"prettier": "^2.8.3",
"ts-node": "^10.9.1",
"ts-node-dev": "^2.0.0",
"vitest": "^0.27.2",
"vitest": "^0.28.3",
"wasm-pack": "^0.10.3"
},
"files": [
Expand Down
12 changes: 6 additions & 6 deletions src/blockchain/block-builder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -99,15 +99,15 @@ const initNewBlock = async (head: Block, header: Header, inherents: HexString[])

{
// initialize block
const { storageDiff } = await newBlock.call('Core_initialize_block', header.toHex())
const { storageDiff } = await newBlock.call('Core_initialize_block', [header.toHex()])
newBlock.pushStorageLayer().setAll(storageDiff)
logger.trace(truncate(storageDiff), 'Initialize block')
}

// apply inherents
for (const extrinsic of inherents) {
try {
const { storageDiff } = await newBlock.call('BlockBuilder_apply_extrinsic', extrinsic)
const { storageDiff } = await newBlock.call('BlockBuilder_apply_extrinsic', [extrinsic])
newBlock.pushStorageLayer().setAll(storageDiff)
logger.trace(truncate(storageDiff), 'Applied inherent')
} catch (e) {
Expand Down Expand Up @@ -142,7 +142,7 @@ export const buildBlock = async (
// apply extrinsics
for (const extrinsic of extrinsics) {
try {
const { storageDiff } = await newBlock.call('BlockBuilder_apply_extrinsic', extrinsic)
const { storageDiff } = await newBlock.call('BlockBuilder_apply_extrinsic', [extrinsic])
newBlock.pushStorageLayer().setAll(storageDiff)
logger.trace(truncate(storageDiff), 'Applied extrinsic')
} catch (e) {
Expand All @@ -153,7 +153,7 @@ export const buildBlock = async (

{
// finalize block
const { storageDiff } = await newBlock.call('BlockBuilder_finalize_block', '0x')
const { storageDiff } = await newBlock.call('BlockBuilder_finalize_block', [])

newBlock.pushStorageLayer().setAll(storageDiff)
logger.trace(truncate(storageDiff), 'Finalize block')
Expand Down Expand Up @@ -221,14 +221,14 @@ export const dryRunExtrinsic = async (

defaultLogger.info({ call: call.toHuman() }, 'dry_run_call')

return newBlock.call('BlockBuilder_apply_extrinsic', generic.toHex())
return newBlock.call('BlockBuilder_apply_extrinsic', [generic.toHex()])
}

defaultLogger.info(
{ call: registry.createType('GenericExtrinsic', hexToU8a(extrinsic)).toHuman() },
'dry_run_extrinsic'
)
return newBlock.call('BlockBuilder_apply_extrinsic', extrinsic)
return newBlock.call('BlockBuilder_apply_extrinsic', [extrinsic])
}

export const dryRunInherents = async (
Expand Down
4 changes: 2 additions & 2 deletions src/blockchain/block.ts
Original file line number Diff line number Diff line change
Expand Up @@ -203,7 +203,7 @@ export class Block {

get metadata(): Promise<HexString> {
if (!this.#metadata) {
this.#metadata = this.call('Metadata_metadata', '0x').then((resp) => compactHex(hexToU8a(resp.result)))
this.#metadata = this.call('Metadata_metadata', []).then((resp) => compactHex(hexToU8a(resp.result)))
}
return this.#metadata
}
Expand All @@ -220,7 +220,7 @@ export class Block {

async call(
method: string,
args: HexString,
args: HexString[],
storage: [HexString, HexString | null][] = []
): Promise<TaskCallResponse> {
const wasm = await this.wasm
Expand Down
2 changes: 1 addition & 1 deletion src/blockchain/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -151,7 +151,7 @@ export class Blockchain {
async submitExtrinsic(extrinsic: HexString): Promise<HexString> {
const source = '0x02' // External
const args = u8aToHex(u8aConcat(source, extrinsic, this.head.hash))
const res = await this.head.call('TaggedTransactionQueue_validate_transaction', args)
const res = await this.head.call('TaggedTransactionQueue_validate_transaction', [args])
const registry = await this.head.registry
const validity: TransactionValidity = registry.createType('TransactionValidity', res.result)
if (validity.isOk) {
Expand Down
4 changes: 2 additions & 2 deletions src/executor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ export const createProof = async (
export const runTask = async (
task: {
wasm: HexString
calls: [string, HexString][]
calls: [string, HexString[]][]
storage: [HexString, HexString | null][]
mockSignatureHost: boolean
allowUnresolvedImports: boolean
Expand Down Expand Up @@ -124,7 +124,7 @@ export const emptyTaskHandler = {
export const getAuraSlotDuration = _.memoize(async (wasm: HexString, registry: Registry): Promise<number> => {
const result = await runTask({
wasm,
calls: [['AuraApi_slot_duration', '0x']],
calls: [['AuraApi_slot_duration', []]],
storage: [],
mockSignatureHost: false,
allowUnresolvedImports: false,
Expand Down
2 changes: 1 addition & 1 deletion src/genesis-provider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -149,7 +149,7 @@ export class GenesisProvider implements ProviderInterface {
return runTask(
{
wasm: code,
calls: [['Metadata_metadata', '0x']],
calls: [['Metadata_metadata', []]],
storage: [],
mockSignatureHost: false,
allowUnresolvedImports: true,
Expand Down
2 changes: 2 additions & 0 deletions src/rpc/substrate/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import author from './author'
import chain from './chain'
import payment from './payment'
import state from './state'
import system from './system'

Expand All @@ -10,6 +11,7 @@ const handlers: Handlers = {
...chain,
...state,
...system,
...payment,
}

export default handlers
33 changes: 33 additions & 0 deletions src/rpc/substrate/payment.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import { Handlers, ResponseError } from '../shared'
import { hexToU8a } from '@polkadot/util'

const handlers: Handlers = {
payment_queryFeeDetails: async (context, [extrinsic, hash]) => {
const block = await context.chain.getBlock(hash)
if (!block) {
throw new ResponseError(1, `Block ${hash} not found`)
}
const registry = await block.registry
const tx = hexToU8a(extrinsic)
const resp = await block.call('TransactionPaymentApi_query_fee_details', [
registry.createType('Extrinsic', tx).toHex(),
registry.createType('u32', tx.byteLength).toHex(),
])
return resp.result
},
payment_queryInfo: async (context, [extrinsic, hash]) => {
const block = await context.chain.getBlock(hash)
if (!block) {
throw new ResponseError(1, `Block ${hash} not found`)
}
const registry = await block.registry
const tx = hexToU8a(extrinsic)
const resp = await block.call('TransactionPaymentApi_query_info', [
registry.createType('Extrinsic', tx).toHex(),
registry.createType('u32', tx.byteLength).toHex(),
])
return resp.result
},
}

export default handlers
7 changes: 4 additions & 3 deletions src/rpc/substrate/state.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { Block } from '../../blockchain/block'
import { Handlers } from '../shared'
import { Handlers, ResponseError } from '../shared'
import { defaultLogger } from '../../logger'

const logger = defaultLogger.child({ name: 'rpc-state' })
Expand Down Expand Up @@ -37,9 +37,10 @@ const handlers: Handlers = {
state_call: async (context, [method, data, hash]) => {
const block = await context.chain.getBlock(hash)
if (!block) {
return []
throw new ResponseError(1, `Block ${hash} not found`)
}
return (await block.call(method, data)).result
const resp = await block.call(method, [data])
return resp.result
},
state_subscribeRuntimeVersion: async (context, _params, { subscribe }) => {
let update = (_block: Block) => {}
Expand Down
2 changes: 1 addition & 1 deletion src/rpc/substrate/system.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ const handlers: Handlers = {
const head = context.chain.head
const registry = await head.registry
const account = registry.createType('AccountId', address)
const result = await head.call('AccountNonceApi_account_nonce', account.toHex())
const result = await head.call('AccountNonceApi_account_nonce', [account.toHex()])
return registry.createType<Index>('Index', hexToU8a(result.result)).toNumber()
},
}
Expand Down
6 changes: 3 additions & 3 deletions src/run-block.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,13 +16,13 @@ export const runBlock = async (argv: Config) => {
const parent = await block.parentBlock
if (!parent) throw Error('cant find parent block')

const calls: [string, HexString][] = [['Core_initialize_block', header.toHex()]]
const calls: [string, HexString[]][] = [['Core_initialize_block', [header.toHex()]]]

for (const extrinsic of await block.extrinsics) {
calls.push(['BlockBuilder_apply_extrinsic', extrinsic])
calls.push(['BlockBuilder_apply_extrinsic', [extrinsic]])
}

calls.push(['BlockBuilder_finalize_block', '0x' as HexString])
calls.push(['BlockBuilder_finalize_block', []])

const result = await runTask(
{
Expand Down
Loading

0 comments on commit e2d4449

Please sign in to comment.