Last active
April 13, 2019 15:45
-
-
Save abuiles/71ee20d83e2aa7fb52eb66ac4a225f21 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Follow the steps below to play with this: | |
// 1. git clone abuiles/json-xdr && cd json-xdr | |
// 2. yarn install (or npm install) | |
// 3. touch sandbox.js | |
// 4. Paste the content of this file in sandbox.js | |
// 5. Run like `node sandox` | |
const XDR = require('js-xdr') | |
const Cursor = require('cursor') | |
const jsonXDR = require('./dist/index') | |
const types = XDR.config((xdr) => { | |
xdr.typedef("Hash", xdr.opaque(2)); | |
xdr.typedef('Int32', xdr.int()); | |
xdr.struct("Price", [ | |
["n", xdr.lookup("Int32")], | |
["d", xdr.lookup("Int32")], | |
]); | |
xdr.enum("MemoType", { | |
memoNone: 0, | |
memoText: 1, | |
memoId: 2, | |
memoHash: 3, | |
memoReturn: 4, | |
}); | |
xdr.union("Memo", { | |
switchOn: xdr.lookup("MemoType"), | |
switchName: "type", | |
switches: [ | |
["memoNone", xdr.void()], | |
["memoText", "text"], | |
["memoId", "id"] | |
], | |
arms: { | |
text: xdr.string(28), | |
id: xdr.lookup("Int32") | |
}, | |
}); | |
xdr.typedef('CounterInt', xdr.option(xdr.int())); | |
xdr.struct('Event', [ | |
["attendees", xdr.int()], | |
["eventName", xdr.string(50)], | |
["secretSpeakers", xdr.array(xdr.lookup("Hash"), 2)], | |
["speakers", xdr.varArray(xdr.string())], | |
["price", xdr.lookup("Price")], | |
["memo", xdr.lookup("Memo")], | |
['meta', xdr.lookup('TransactionMeta')], | |
['counter', xdr.lookup("CounterInt")] | |
]) | |
xdr.enum("TransactionMetaType", { | |
none: 0, | |
paid: 1 | |
}); | |
xdr.union("TransactionMeta", { | |
switchOn: xdr.lookup("TransactionMetaType"), | |
switches: [ | |
["none", xdr.void()], | |
["paid", "price"] | |
], | |
arms: { | |
price: xdr.lookup("Price") | |
}, | |
defaultArm: xdr.void() | |
}); | |
}) | |
let event = new types.Event({ | |
attendees: 5, | |
eventName: "Lumenauts get together", | |
secretSpeakers: [Buffer.from([0, 0]), Buffer.from([0, 1])], | |
speakers: ['Jed', 'Tom', 'Zac'], | |
price: new types.Price({ | |
n: 2, | |
d: 1 | |
}), | |
memo: types.Memo.memoText("foo"), | |
meta: types.TransactionMeta.paid(new types.Price({ | |
n: 2, | |
d: 1 | |
})), | |
counter: 2 | |
}) | |
let payload = jsonXDR.toJSON(event); | |
let eventCopy = jsonXDR.toXDR(types.Event, payload); | |
console.log(types.Event.fromXDR(eventCopy.toXDR()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment