init
This commit is contained in:
@@ -0,0 +1,148 @@
|
||||
import { PaymentTx_T, ParameterizedFunction, Payload, RJSVM, RJSVM_Config, RJSVM_Endpoint, RJSVM_Implementations, payloadSchema, Function_Map, Endpoints_Of, State_Of, Generic_Ctor_ReturnType } from "./types"
|
||||
import { Client as Xrpl } from 'xrpl';
|
||||
import { xrpIO } from 'xrpio';
|
||||
import { DataParser } from "../../util/dataparser";
|
||||
import { XRP_ADDRESS } from "../../util/protocol.constants";
|
||||
|
||||
|
||||
export abstract class RJSVM_Builder {
|
||||
static from<
|
||||
Base_Ctor extends (new (...args: any) => RJSVM<State_T, Endpoints_T>) | (abstract new (...args: any) => RJSVM<State_T, Endpoints_T>),
|
||||
Impl extends RJSVM_Implementations<any, Endpoints_T>,
|
||||
Endpoints_T extends Function_Map = Endpoints_Of<Generic_Ctor_ReturnType<Base_Ctor>>,
|
||||
State_T = State_Of<Generic_Ctor_ReturnType<Base_Ctor>>
|
||||
>(Base: Base_Ctor, defs: Impl): (new (config: RJSVM_Config) => RJSVM<State_T, Endpoints_T>){
|
||||
return <any> class RJSVM_Runnable extends (Base as any){
|
||||
|
||||
sync_block_height = -1
|
||||
|
||||
private rippleApi: Xrpl
|
||||
private xrpIO: xrpIO
|
||||
public readonly definitions: Impl
|
||||
|
||||
constructor(
|
||||
public readonly config: RJSVM_Config
|
||||
) {
|
||||
super()
|
||||
|
||||
|
||||
if(!XRP_ADDRESS.test(this.owner)){
|
||||
throw new Error(`Inavlid owner address ${this.owner}`)
|
||||
}
|
||||
|
||||
|
||||
this.definitions = Object.freeze(defs)
|
||||
Object.entries(this.definitions).forEach(([k, v]) => {
|
||||
this[k] = (env: PaymentTx_T, ...args: any) => (v.implementation as ParameterizedFunction).apply(this as any, [env, ...args])
|
||||
})
|
||||
}
|
||||
|
||||
public connect = async () => {
|
||||
this.rippleApi = new Xrpl(this.config.rippleNode)
|
||||
await this.rippleApi.connect()
|
||||
|
||||
this.xrpIO = new xrpIO(this.config.rippleNode);
|
||||
await this.xrpIO.connect()
|
||||
await this.sync()
|
||||
|
||||
this.rippleApi.on('ledgerClosed', (ledger: any) => {
|
||||
/*
|
||||
console.log("---- Ledger ----")
|
||||
console.log("index",ledger.ledger_index)
|
||||
console.log("hash", ledger.ledger_hash)
|
||||
console.log("---- /Ledger ----")
|
||||
*/
|
||||
})
|
||||
await this.rippleApi.request({
|
||||
command: 'subscribe',
|
||||
streams: ['ledger']
|
||||
})
|
||||
}
|
||||
|
||||
private handlePayload = async (tx: PaymentTx_T, payload: Payload) => {
|
||||
if (!(payload.endpoint in this.definitions)) {
|
||||
return
|
||||
}
|
||||
|
||||
const endpointDef: RJSVM_Endpoint<RJSVM, any> = this.definitions[payload.endpoint]
|
||||
|
||||
|
||||
if(endpointDef.visibility === 'owner' && tx.Account !== this.owner){
|
||||
console.log(`owner restricted endpoint "${payload.endpoint}" called from ${tx.hash}. But ${tx.Account} != ${this.owner}`)
|
||||
return
|
||||
}
|
||||
|
||||
if(endpointDef.fee && Number(tx.Amount) < endpointDef.fee){
|
||||
console.log(`Insufficient fee ${tx.hash}. Required ${endpointDef.fee}, was ${tx.Amount}`)
|
||||
return
|
||||
}
|
||||
|
||||
try {
|
||||
const data = await this.xrpIO.treeRead([payload.data], tx.Account)
|
||||
const jsonData = JSON.parse(data)
|
||||
endpointDef.parameterSchema.parse(jsonData)
|
||||
this[payload.endpoint].apply(this, [tx, jsonData])
|
||||
} catch (err) {
|
||||
console.log(err)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
private parseMemos = async (tx:PaymentTx_T, memos: any[]) => {
|
||||
memos
|
||||
.map((memo: any) => {
|
||||
if (!memo.Memo || !memo.Memo.MemoData) {
|
||||
return
|
||||
}
|
||||
try {
|
||||
const data = DataParser.hex_to_ascii(memo.Memo.MemoData)
|
||||
return JSON.parse(data)
|
||||
} catch (e) {
|
||||
return
|
||||
}
|
||||
})
|
||||
.filter((data: string) => data != undefined)
|
||||
.forEach(payload => {
|
||||
try {
|
||||
const parsedPayload = payloadSchema.parse(payload)
|
||||
this.handlePayload(tx, parsedPayload)
|
||||
} catch (e) {
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
private sync = async (marker?: any): Promise<void> => {
|
||||
//If `forward` is set to true, returns values indexed with the oldest ledger first.
|
||||
//Otherwise, the results are indexed with the newest ledger first.
|
||||
//(Each page of results may not be internally ordered, but the pages are overall ordered.)
|
||||
|
||||
const resp = await this.rippleApi.request({
|
||||
command: "account_tx",
|
||||
account: this.config.listeningAddress,
|
||||
forward: true,
|
||||
ledger_index_min: this.sync_block_height,
|
||||
marker: marker,
|
||||
})
|
||||
|
||||
//results may not be ordered, so sort them
|
||||
const raw_txs = resp.result.transactions
|
||||
.sort((a,b) => a.tx.ledger_index - b.tx.ledger_index)
|
||||
.map((entry: any) => entry.tx)
|
||||
|
||||
//apply any state changes
|
||||
await Promise.all(raw_txs.map((tx: PaymentTx_T) => this.parseMemos(tx, tx.Memos)))
|
||||
|
||||
//if marker is present the result is paginated.
|
||||
//re-run the same request with the marker included
|
||||
if(resp.result.marker){
|
||||
await this.sync(resp.result.marker)
|
||||
}else{
|
||||
//presence of no marker means we caught up to current block height
|
||||
this.sync_block_height = resp.result.ledger_index_max + 1
|
||||
//schedule the next sync
|
||||
setTimeout(this.sync, 10000)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
import { z } from "zod";
|
||||
|
||||
export abstract class RJSVM<State_T = any, Definitions_T extends Function_Map = Function_Map>{
|
||||
owner: string
|
||||
state: State_T
|
||||
sync_block_height: number
|
||||
config: RJSVM_Config
|
||||
definitions: RJSVM_Implementations<any, Definitions_T>
|
||||
connect: () => Promise<void>
|
||||
}
|
||||
|
||||
export type Generic_Ctor_ReturnType<Ctor>
|
||||
= Ctor extends new (...args:any) => infer T ? T
|
||||
: Ctor extends abstract new (...args:any) => infer A ? A
|
||||
: never
|
||||
|
||||
export type State_Of<T extends RJSVM<any>> = T extends RJSVM<infer State_T> ? State_T : any
|
||||
export type Endpoints_Of<T extends RJSVM<any, any>> = T extends RJSVM<any, infer Endpoints_T> ? Endpoints_T : any
|
||||
|
||||
|
||||
export type PaymentTx_T = {
|
||||
Account: string,
|
||||
Amount: string,
|
||||
Destination: string,
|
||||
Fee: string,
|
||||
Flags: number,
|
||||
LastLedgerSequence: number,
|
||||
Memos: any[],
|
||||
Sequence: number,
|
||||
SigningPubKey: string,
|
||||
TransactionType: 'Payment',
|
||||
TxnSignature: string,
|
||||
date: number,
|
||||
hash: string,
|
||||
inLedger: number,
|
||||
ledger_index: number
|
||||
}
|
||||
|
||||
export type ParameterizedFunction = (...args: any) => void
|
||||
|
||||
export type Function_Map = {
|
||||
[K in string]: ParameterizedFunction
|
||||
}
|
||||
|
||||
export type RJSVM_Endpoint<
|
||||
RJSVM_T extends RJSVM<any, Definitions_T>,
|
||||
Definitions_T extends Function_Map = Endpoints_Of<RJSVM_T>,
|
||||
Impl extends RJSVM_EndpointHandler<RJSVM_T, Definitions_T, ParameterizedFunction> = RJSVM_EndpointHandler<RJSVM_T, Definitions_T, ParameterizedFunction>
|
||||
> = {
|
||||
implementation: Impl
|
||||
visibility: 'owner' | 'public'
|
||||
fee?: number,
|
||||
parameterSchema: z.Schema
|
||||
}
|
||||
|
||||
export type RJSVM_Implementations<
|
||||
RJSVM_T extends RJSVM<any, Definitions>,
|
||||
Definitions extends Function_Map = Endpoints_Of<RJSVM_T>,
|
||||
> = {
|
||||
[Key in keyof Definitions]: RJSVM_Endpoint<RJSVM_T, Definitions, RJSVM_EndpointHandler<RJSVM_T, Definitions, Definitions[Key]>>
|
||||
}
|
||||
|
||||
export type RJSVM_EndpointHandler<
|
||||
RJSVM_T extends RJSVM<any, Definitions_T>,
|
||||
Definitions_T extends Function_Map = Endpoints_Of<RJSVM_T>,
|
||||
Fn extends ParameterizedFunction = ParameterizedFunction,
|
||||
> =
|
||||
(this: RJSVM_T & RJSVM_Interface<RJSVM_T, State_Of<RJSVM_T>, Definitions_T>, env: PaymentTx_T, ...args: Parameters<Fn>) => void
|
||||
|
||||
export type RJSVM_Interface<
|
||||
RJSVM_T extends RJSVM<State_T, Definitions_T>,
|
||||
State_T = State_Of<RJSVM_T>,
|
||||
Definitions_T extends Function_Map = Endpoints_Of<RJSVM_T>,
|
||||
> = {
|
||||
state: State_T
|
||||
} & {
|
||||
[K in keyof Definitions_T]?: RJSVM_EndpointHandler<RJSVM_T, Definitions_T, Definitions_T[K]>
|
||||
}
|
||||
|
||||
export type RJSVM_InitState<State_T> = {
|
||||
owner: string,
|
||||
state: State_T
|
||||
}
|
||||
|
||||
export type RJSVM_Config = {
|
||||
rippleNode: string,
|
||||
listeningAddress: string
|
||||
}
|
||||
|
||||
export const payloadSchema = z.object({
|
||||
endpoint: z.string(),
|
||||
data: z.string()
|
||||
})
|
||||
|
||||
export type Payload = z.infer<typeof payloadSchema>
|
||||
@@ -0,0 +1,79 @@
|
||||
import { xrpIO } from "xrpio";
|
||||
|
||||
type Wallet = {
|
||||
address: string,
|
||||
secret: string
|
||||
}
|
||||
|
||||
type DatawriterConfig = {
|
||||
receiveAddress: string
|
||||
sendWallet: Wallet
|
||||
xrpNode: string
|
||||
contractAddress: string
|
||||
}
|
||||
|
||||
export class Datawriter {
|
||||
|
||||
constructor(private config: DatawriterConfig) {
|
||||
}
|
||||
|
||||
|
||||
async callEndpoint(endpointName: string, parameter: any, fee?: number) {
|
||||
const xrpio: xrpIO = new xrpIO(this.config.xrpNode)
|
||||
await xrpio.connect()
|
||||
try{
|
||||
const dataHash = await xrpio.treeWrite(
|
||||
JSON.stringify(parameter),
|
||||
this.config.receiveAddress,
|
||||
this.config.sendWallet.secret
|
||||
)
|
||||
await xrpio.writeRaw(
|
||||
{
|
||||
data: JSON.stringify({
|
||||
endpoint: endpointName,
|
||||
data: dataHash
|
||||
})
|
||||
},
|
||||
this.config.contractAddress,
|
||||
this.config.sendWallet.secret,
|
||||
undefined,
|
||||
fee ? String(fee) : undefined
|
||||
)
|
||||
}catch(e){
|
||||
console.log(e)
|
||||
}finally{
|
||||
await xrpio.disconnect()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
(async () => {
|
||||
const owner_dw = new Datawriter({
|
||||
receiveAddress: "rDuXvMYNCEJCYDMFQykcafXhgi2NvMWqR",
|
||||
sendWallet: {
|
||||
address: "rUsPfG1hn6w6is28p5FUDWdMwvCo1iHrYq",
|
||||
secret: "sEdTMicaTVmfsVMLhxrufyAzEQSnsaP"
|
||||
},
|
||||
xrpNode: "wss://s.altnet.rippletest.net:51233",
|
||||
contractAddress: 'rLaXUiYvW1EMns69PsAfwSLb2VgNtPpZwq'
|
||||
})
|
||||
|
||||
//await owner_dw.callEndpoint('submit', { title: "1", body: "2", from: "3" }, 100)
|
||||
|
||||
const user_dw = new Datawriter({
|
||||
receiveAddress: "rwqCiEr3SLF43rAduhCChkR2K1XDhiqx5g",
|
||||
sendWallet: {
|
||||
address: "rHWN4X3hbodryX8H1EoPvmMV7AFHngEiBe",
|
||||
secret: "sEdTdLPWvz69UAUmt1zYijTyWheER9u"
|
||||
},
|
||||
xrpNode: "wss://s.altnet.rippletest.net:51233",
|
||||
contractAddress: 'rLaXUiYvW1EMns69PsAfwSLb2VgNtPpZwq'
|
||||
})
|
||||
|
||||
//await owner_dw.callEndpoint('submit', { title: "1", body: "2", from: "3" }, 100)
|
||||
//await user_dw.callEndpoint('restricted', { title: "user", body: "user", from: "user" })
|
||||
//await owner_dw.callEndpoint('restricted', { title: "owner", body: "owner", from: "owner" })
|
||||
|
||||
await user_dw.callEndpoint('setTns', { hash: '01708abcF00636CE10E191FD782DBDC8F4076F28404BD88EBC31DE42DD084C0944B', name: 'test'})
|
||||
|
||||
})()
|
||||
@@ -0,0 +1,3 @@
|
||||
export * from "./RJSVM/framework/rjsvm"
|
||||
export * from "./RJSVM/framework/types"
|
||||
export * from "./util/dataparser"
|
||||
@@ -0,0 +1,78 @@
|
||||
import { z } from "zod";
|
||||
import { RJSVM_Implementations, RJSVM_Interface, RJSVM, RJSVM_Config, RJSVM_InitState } from "./RJSVM/framework/types"
|
||||
import { RJSVM_Builder } from "./main";
|
||||
import { xrp_transaction_hash_schema } from "./util/schemas";
|
||||
|
||||
const shoutSchema = z.object({
|
||||
title: z.string(),
|
||||
body: z.string(),
|
||||
from: z.string(),
|
||||
id: z.optional(z.string())
|
||||
})
|
||||
type Shout = z.infer<typeof shoutSchema>
|
||||
|
||||
const tnsEntrySchema = z.object({
|
||||
hash: xrp_transaction_hash_schema,
|
||||
name: z.string(),
|
||||
})
|
||||
type TnsEntry = z.infer<typeof tnsEntrySchema>
|
||||
|
||||
type State = {
|
||||
shouts: Shout[]
|
||||
}
|
||||
|
||||
type RJSVM_Endpoints = {
|
||||
submit: (data: Shout) => void
|
||||
restricted: (data: Shout) => void
|
||||
setTns: (entry: TnsEntry) => void
|
||||
}
|
||||
|
||||
abstract class RJSVM_Base
|
||||
extends RJSVM<State, RJSVM_Endpoints>
|
||||
implements RJSVM_Interface<RJSVM_Base> {
|
||||
owner = "rUsPfG1hn6w6is28p5FUDWdMwvCo1iHrYq"
|
||||
|
||||
state: State = {
|
||||
shouts: []
|
||||
}
|
||||
}
|
||||
|
||||
const RJSVM_Contract: RJSVM_Implementations<RJSVM_Base> = {
|
||||
submit: {
|
||||
implementation: function (env, shout) {
|
||||
this.state.shouts.unshift(shout)
|
||||
console.log(shout)
|
||||
},
|
||||
visibility: 'public',
|
||||
fee: 10,
|
||||
parameterSchema: shoutSchema
|
||||
},
|
||||
|
||||
restricted: {
|
||||
implementation: function (env, shout) {
|
||||
this.state.shouts.unshift(shout)
|
||||
console.log(shout)
|
||||
},
|
||||
visibility: 'owner',
|
||||
parameterSchema: shoutSchema
|
||||
},
|
||||
setTns: {
|
||||
implementation: function (env, tnsEntry) {
|
||||
console.log(tnsEntry)
|
||||
},
|
||||
visibility: 'public',
|
||||
parameterSchema: tnsEntrySchema,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
const Rjsvm = RJSVM_Builder.from(RJSVM_Base, RJSVM_Contract);
|
||||
|
||||
const conf: RJSVM_Config = {
|
||||
listeningAddress: "rLaXUiYvW1EMns69PsAfwSLb2VgNtPpZwq",
|
||||
rippleNode: "wss://s.altnet.rippletest.net:51233"
|
||||
}
|
||||
|
||||
const rjsvm = new Rjsvm(conf)
|
||||
|
||||
rjsvm.connect()
|
||||
@@ -0,0 +1,10 @@
|
||||
export class DataParser {
|
||||
public static hex_to_ascii(input: any) {
|
||||
var hex = input.toString();
|
||||
var str = '';
|
||||
for (var n = 0; n < hex.length; n += 2) {
|
||||
str += String.fromCharCode(parseInt(hex.substr(n, 2), 16));
|
||||
}
|
||||
return str;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
export const MSG_DELIM: string = ' '
|
||||
export const MSG_DATA_MAX: number = 925
|
||||
export const PUBKEY_LEN: number = 66
|
||||
export const NON_ZERO_TX_HASH = new RegExp(`[0-9A-F]{64}`)
|
||||
export const PTR_FORMAT = new RegExp(`^((${NON_ZERO_TX_HASH.source})|0)`)
|
||||
export const DATA_FORMAT = new RegExp(`(.{1,${MSG_DATA_MAX}})`)
|
||||
export const SIGNATURE_FORMAT = new RegExp(`(\\S{140}|\\S{142})$`)
|
||||
export const SIGNER_FORMAT = new RegExp(`(\\S{${PUBKEY_LEN}})`)
|
||||
export const MSG_FORMAT = new RegExp(`${PTR_FORMAT.source}${MSG_DELIM}${DATA_FORMAT.source}`, 'm')
|
||||
export const AMOUNT_DECIMALS = 18
|
||||
export const MAX_SUPPLY = 20_000_000
|
||||
export const AMOUNT_FORMAT = new RegExp(`\d+(\.\d{1,${AMOUNT_DECIMALS}})?`)
|
||||
export const MIN_XRP_FEE = "0.00001"
|
||||
export const MIN_XRP_TX_VALUE = "0.000001"
|
||||
export const XRP_ADDRESS = new RegExp(`^([r])([1-9A-HJ-NP-Za-km-z]{24,34})`)
|
||||
@@ -0,0 +1,6 @@
|
||||
import { z } from "zod";
|
||||
import { XRP_ADDRESS } from "./protocol.constants";
|
||||
import { NON_ZERO_TX_HASH } from "xrpio";
|
||||
|
||||
export const xrp_address_schema = z.string().regex(XRP_ADDRESS, "Not a valid XRP address")
|
||||
export const xrp_transaction_hash_schema = z.string().regex(NON_ZERO_TX_HASH, "Not a valid XRP transaction hash")
|
||||
Reference in New Issue
Block a user