wietsewind's notebooks

  • Secret Numbers Rollover - /wietsewind/secret-numbers-rollover
    Last edited 2 days ago
    const {Account, Utils} = require('xrpl-secret-numbers') const tests = { 'uInt16': 34462, 'Rollover (uInt16)': 34462 + parseInt('10000', 16) } Object.keys(tests).map(k => { const secretNumbers = Array(8).fill(tests[k]).map((_, i) => { return String(_) + Utils.calculateChecksum(i, _) }) const familySeed = new Account(secretNumbers).getFamilySeed() console.log(`${k}: ${familySeed}`, secretNumbers.join(' ')) })
  • MomentJS XUMM objects - /wietsewind/momentjs-xumm-objects
    Last edited 19 days ago
    const fetch = require('node-fetch') const moment = require('moment/min/moment-with-locales') exports.endpoint = async (req, res) => { const momentLocalesCall = await fetch('https://api.github.com/repositories/1424470/contents/src/locale') const momentLocalesJson = await momentLocalesCall.json() const momentLocalesData = momentLocalesJson.map(l => l.name.split('.')[0]) const xummLocalesCall = await fetch('https://translate.xumm.dev/json/export-meta') const xummLocalesJson = await xummLocalesCall.json() if (res !== null) { res.setHeader('Content-Type', 'application/json; Charset=UTF-8') res.setHeader('Access-Control-Allow-Origin', '*') res.setHeader('Access-Control-Allow-Methods', '*') } const xummLocaleToMomentJsLocale = Object.keys(xummLocalesJson.languages) .reduce((a, b) => { let resolvedLocale = 'en' if (momentLocalesData.indexOf(b.toLowerCase()) > -1) { resolvedLocale = b.toLowerCase() } else if (momentLocalesData.indexOf(b.split('-')[0].toLowerCase()) > -1) { resolvedLocale = b.split('-')[0].toLowerCase() } else { // Check alias const aliasses = Object.keys(xummLocalesJson['language-code-alias']).filter(k => { return xummLocalesJson['language-code-alias'][k].toLowerCase() === b.toLowerCase() }) if (aliasses.length > 0) { aliasses.forEach(a => { const alias = a.toLowerCase().replace('_', '-') if (momentLocalesData.indexOf(alias) > -1) { resolvedLocale = alias } }) } } moment.locale(resolvedLocale) const localeData = moment.localeData() Object.assign(a, { [b]: { momentJsCode: resolvedLocale, momentJsSource: Object.keys(localeData).reduce((c, d) => { if ( ['RegExp', 'Function'].indexOf(localeData[d].constructor.name) < 0 && !d.match(/(Parse|Regex)$/) && d !== '_config' ) { Object.assign(c, { [d.replace(/^_/, '')]: localeData[d] }) } return c }, {}) } }) return a }, {}) if (res !== null) { return res.end(JSON.stringify(xummLocaleToMomentJsLocale)) } else { // return console.log(xummLocaleToMomentJsLocale.nl.momentJsSource) return console.log(xummLocaleToMomentJsLocale) } } exports.endpoint(null, null)
  • Monitor XRPL Testnet Servers - /wietsewind/monitor-xrpl-testnet-servers
    Last edited 19 days ago
    const WebSocket = require('websocket').client const ServersToTest = [ 'testnet.xrpl-labs.com', 's.altnet.rippletest.net:51233' ] exports.endpoint = (request, response) => { Promise.all(ServersToTest.map(Server => { return new Promise((resolve, reject) => { let WsInstance = new WebSocket() WsInstance.connect('wss://' + Server) WsInstance.on('connectFailed', error => { console.log('Connect Error ' + Server, error.toString()) resolve({ server: Server, status: 'ConnectError', data: null, errorData: error.toString() }) }) WsInstance.on('connect', c => { // console.log('Connected ' + Server, c) c.on('message', m => { let data = JSON.parse(m.utf8Data) // console.log('Message ' + Server, data) resolve({ server: Server, status: 'Response', data: data, errorData: null }) c.close() }) c.on('close', () => { // console.log('Closed ' + Server) }) c.on('error', e => { console.log('Error ' + Server, e.toString()) resolve({ server: Server, status: 'MsgError', data: null, errorData: e.toString() }) }) c.send(JSON.stringify({ command: 'server_info' })) setTimeout(() => { c.close() resolve({ server: Server, status: 'Timeout', data: null, errorData: null }) }, 5000) }) }) })).then(Results => { // Running in the browser, respond let highestLedger = Math.max.apply(Math, Results.filter(r => { return r.status === 'Response' && r.data !== null && r.data.result.info.complete_ledgers.match(/[0-9]/) }).map(r => { return parseInt(r.data.result.info.complete_ledgers.split(',').reverse()[0].split('-').reverse()[0]) }).filter(r => { return !isNaN(r) })) let OutputData = { highestLedger: highestLedger, responses: Object.assign({}, ...Results.map(r => { let lastLedger = 0 if (r.data !== null) { lastLedger = parseInt(r.data.result.info.complete_ledgers.split(',').reverse()[0].split('-').reverse()[0]) if (isNaN(lastLedger)) lastLedger = 0 } return { [r.server.replace(/[^a-z0-9]/g, '')]: Object.assign(r, { lastLedger: lastLedger, ledgerOffset: highestLedger - lastLedger }) } })) } if (response !== null) { response.end(JSON.stringify(OutputData)) } else { // Running in the console. Log. console.log('Done', OutputData) } }).catch(Error => { }) } // When in the browser... exports.endpoint(null, null)
  • XRPL Buffer to Seed to Account - /wietsewind/xrpl-buffer-to-seed-to-account
    Last edited a month ago
    const kp = require('ripple-keypairs') const hex = '0123456789ABCDEF0123456789ABCDEF' // const entropy = Buffer.from(hex, 'hex') // console.log(entropy) // const secret = kp.generateSeed({entropy}) // const secret = kp.generateSeed({algorithm:'ed25519'}) // const pair = kp.deriveKeypair(secret) // const wallet = kp.deriveAddress(pair.publicKey) const wallet = kp.deriveAddress('ED' + 'A6CADFC1BF20EC6FC356FED95822A90C93D6ED410E2EB9F1F7DFFB8D066986F5') // console.log('Pair', pair) // console.log('Secret', secret) console.log('Address', wallet)
  • Simple XRPL Sha512-half keypair - /wietsewind/simple-xrpl-keypair
    Last edited 2 months ago
    const crypto = require('crypto') const rippleSecretCodec = require('ripple-secret-codec') const rippleKeypairs = require('ripple-keypairs') const passphrase = 'masterpassphrase' const hexSeed = crypto.createHash('sha512').update(passphrase).digest('hex').toUpperCase().substring(0, 32) console.log('hexSeed: ' + hexSeed) const secret = rippleSecretCodec.encodeHex(hexSeed).secret_b58 console.log('Secret: ' + secret) const keypair = rippleKeypairs.deriveKeypair(secret) const address = rippleKeypairs.deriveAddress(keypair.publicKey) const wallet = { address: address, secret: secret }
  • Parse UNL - /wietsewind/parse-unl
    Last edited 3 months ago
    const fetch = require('node-fetch') const {decode} = require('ripple-binary-codec') const {encodeNodePublic} = require('ripple-address-codec') const base64ToDecoded = base64 => decode(Buffer.from(base64, 'base64').toString('hex')) const pubkeyToNode = pubhex => encodeNodePublic(Buffer.from(pubhex, 'hex')) const main = async () => { const f = await fetch('http://vl.ripple.com/') const {manifest, blob} = await f.json() const {validators} = JSON.parse(Buffer.from(blob, 'base64').toString('utf-8')) return validators.map(v => { const manifest = base64ToDecoded(v.manifest) return { validation_public_key: v.validation_public_key, decodedManifestPubKeys: { PublicKey: pubkeyToNode(manifest.PublicKey), SigningPubKey: pubkeyToNode(manifest.SigningPubKey) }, manifest } }) } console.log(await main())
  • XUMM SDK - /wietsewind/xumm-sdk
    Last edited 4 months ago
    const {XummSdk} = require('xumm-sdk') const Sdk = new XummSdk('xxxx-xxxx', 'xxxx') const main = async () => { const payload = { txjson: { TransactionType: 'Payment', Destination: 'rPEPPER7kfTD9w2To4CQk6UCfuHM9c6GDY', DestinationTag: 495, Amount: 1000000 } } const createdPayload = await Sdk.payload.create(payload, true) console.log({createdPayload}) } main()
  • Get XRPL Exchanged Value - /wietsewind/get-xrpl-exchanged-value
    Last edited 5 months ago
    const Client = require('rippled-ws-client') const TxParser = require('ripple-lib-transactionparser') const main = async () => { console.log('Connecting') const connection = await new Client('wss://xrpl.ws') console.log('Connected, requesting transaction') const transaction = await connection.send({ command: 'tx', transaction: '63488A0526DC0196AB89DD7DAE2A972A2E75808086287C02587603E8C46B6532' }) console.log('Tx by Account', transaction.Account) console.log(TxParser.parseBalanceChanges(transaction.meta)[transaction.Account]) return connection.close() } main()
  • XRPL IOU Fee Rate calc. - /wietsewind/xrpl-iou-fee-rate-calc
    Last edited 6 months ago
    const BigNumber = require('bignumber.js') const availableBalance = new BigNumber(10) const currency = { transfer_rate: '1050000000' } const one = new BigNumber(1) const rate = new BigNumber(currency.transfer_rate).dividedBy(10000000).minus(100) // Percentage const fee = new BigNumber(availableBalance).times(one.minus(one.dividedBy(one.plus(rate.dividedBy(100))))) const maxCanSend = availableBalance.minus(fee).toNumber() console.log({ rate: rate.toNumber(), fee: fee.toNumber(), maxCanSend })
  • Calc XRPL Check ID - /wietsewind/calc-xrpl-check-id
    Last edited 7 months ago
    const crypto = require('crypto') const ra = require('ripple-address-codec') const a = Buffer.from('0043', 'hex') const b = ra.decodeAccountID('rtaBqey87MpBcbrbv3qjtNCUchwag2vMv') const c = Buffer.alloc(4) c.writeUInt32BE(225) // Create Sequence const all = Buffer.concat([a, b, c]) console.log(all) const sha = crypto.createHash('sha512').update(all) const result = sha.digest('hex') console.log(result.toUpperCase().slice(0, 64))