Compare commits

...

57 Commits

Author SHA1 Message Date
muzam1l
513db7bf09 Update asc. 2023-03-31 14:22:33 +05:30
muzam1l
969fd0f63c Merge branch 'main' into feat/ts-support. 2023-03-31 14:20:04 +05:30
muzamil
412e3f2bbf Merge pull request #303 from XRPLF/fix/hex-value
Take tx memo data and parameter value as hex.
2023-03-29 17:43:11 +05:30
muzam1l
dc37b1911a Take tx memo data and parameter value as hex. 2023-03-29 15:04:14 +05:30
muzamil
c348868c89 Merge pull request #302 from XRPLF/fix/hook-on
Fix HookOn initial value.
2023-03-28 16:28:35 +05:30
muzam1l
2c3cfebe3a Fix HookOn initial value. 2023-03-28 15:14:43 +05:30
muzamil
6265a9cdbf Merge pull request #300 from XRPLF/fix/to-hex
Fix hex logic.
2023-03-27 21:20:08 +05:30
muzamil
1321b498cf Merge pull request #299 from XRPLF/fix/invoke-tx
Add `Destination` field to Invoke transaction.
2023-03-27 21:18:35 +05:30
muzam1l
801d9778cb Fix hex logic. 2023-03-27 19:21:14 +05:30
muzam1l
2cf18ef61c Add Destination field to Invoke transaction. 2023-03-27 15:32:25 +05:30
muzamil
4d2dc16ce5 Merge pull request #296 from XRPLF/feat/account-ui
Extend transactions Account UI.
2023-03-23 20:45:27 +05:30
muzam1l
9ecf5478e6 Remove tx Destination default values. 2023-03-23 19:39:56 +05:30
muzam1l
6d1ef110b7 Token Issuer account UI. 2023-03-23 17:52:17 +05:30
muzam1l
b9edfcd63b Fix: nextjs build. 2023-03-23 16:55:32 +05:30
muzam1l
b653d9a9cb Fix: Remove last traces of custom Destination handling! 2023-03-23 16:47:25 +05:30
muzam1l
da28e0a7d1 Use "creatable select" for accounts. 2023-03-23 16:45:24 +05:30
muzam1l
8a5b83d57f Fix: Don't remove fields in JSON mode if empty. 2023-03-23 16:26:29 +05:30
muzam1l
025eff6cf2 Add Select UI for account. 2023-03-23 16:12:35 +05:30
muzam1l
62d521b2cc Add owner field to NFTokenCreateOffer. 2023-03-23 15:51:36 +05:30
muzam1l
7aafca21df Remove Destination as special field. 2023-03-23 15:49:17 +05:30
muzamil
80f58e903c Merge pull request #294 from XRPLF/feat/amount-ui
Transaction amount UI.
2023-03-20 14:04:30 +05:30
muzam1l
c4af3df017 Add DeliverMin field to tx CheckCash. 2023-03-17 20:10:57 +05:30
muzam1l
5d8d142bc4 Catch all estimate fee errors. 2023-03-17 19:01:32 +05:30
muzam1l
e27a71d713 Estimate fee correct error message and amount input type. 2023-03-17 18:57:03 +05:30
muzam1l
e08b07cbeb Update tx OfferCreate. 2023-03-17 18:03:37 +05:30
muzam1l
e4936c03ef Css changes. 2023-03-17 17:17:29 +05:30
muzam1l
21a69ac8ea minor type fix. 2023-03-17 16:59:12 +05:30
muzam1l
52e4f219f7 Transaction amount UI. 2023-03-17 16:49:00 +05:30
muzamil
e1f34c4beb Merge pull request #291 from XRPLF/fix/sequence-ui
Fix Account sequence UI reset.
2023-03-14 21:30:35 +05:30
muzam1l
54a89c969e Fix account sequence reset. 2023-03-14 15:38:09 +05:30
muzamil
ded867d997 Merge pull request #289 from XRPLF/fix/tx
Account sequence.
2023-03-10 17:31:55 +05:30
muzam1l
0fce9af77c Fetch sequence on account creation. 2023-03-10 16:18:35 +05:30
muzam1l
55c68c580a Account Sequence UI. 2023-03-10 16:02:32 +05:30
muzamil
832a7997d1 Merge pull request #288 from XRPLF/fix/tx
Fix tx json saving and discarding.
2023-03-08 21:32:36 +05:30
muzam1l
4528e5a16e Actually fix Json 'save'. 2023-03-08 20:33:23 +05:30
muzam1l
38f064c6d8 Fix json saving and discarding. 2023-03-08 17:13:36 +05:30
muzamil
fbf4565dbc Merge pull request #287 from XRPLF/feat/memos-ui
Memos UI
2023-03-07 17:32:32 +05:30
muzam1l
9001c64fed minor label changes. 2023-03-07 16:58:32 +05:30
muzam1l
03b768db4e UI for memos fields. 2023-03-07 16:03:47 +05:30
muzam1l
825af0db89 Add memos field in transactions. 2023-03-06 21:14:14 +05:30
muzamil
31043f33ab Merge pull request #286 from XRPLF/feat/tx-params-ui
HookParameters UI for transactions.
2023-03-06 16:06:19 +05:30
muzam1l
bd1a0c9836 Remove some logs. 2023-02-21 16:30:01 +05:30
muzam1l
ba95eb5be2 Merge branch 'main' into feat/ts-support 2023-02-20 19:52:33 +05:30
muzam1l
6911bcc0f3 Upgrade to official @eqlabs/assemblyscript. 2023-02-20 19:33:54 +05:30
muzam1l
a6055feb1f update asc (top level return) 2023-02-03 15:26:24 +05:30
muzam1l
31a185f49f Enable top level api. 2023-02-02 17:44:15 +05:30
muzam1l
d693458421 fix wat state not updating. 2023-02-01 21:58:25 +05:30
muzam1l
692bbeb9b2 minor fixes. 2023-02-01 04:27:10 +05:30
muzam1l
a29368d633 update wabt 1.0.30 -> 1.0.32 2023-01-30 15:41:42 +05:30
muzam1l
0f32fcb71c asc 0.0.8. 2023-01-19 20:05:07 +05:30
muzam1l
90db6b1f12 assemblyscript 0.0.6. 2023-01-16 18:36:25 +05:30
muzam1l
dde0317544 Update assemblyscript. 2023-01-13 14:36:26 +05:30
muzam1l
a6ad39f6e8 Update nextjs. 2023-01-11 21:08:17 +05:30
muzam1l
0536e48cfe Fix some type errors. 2023-01-11 20:17:21 +05:30
muzam1l
a08823a38b Better lang warning. 2023-01-11 20:01:02 +05:30
muzam1l
653e28583d Compile ts files. 2023-01-11 19:52:45 +05:30
muzam1l
e75443c8e2 Detect ts files. 2023-01-06 19:58:03 +05:30
37 changed files with 1961 additions and 935 deletions

1
.gitignore vendored
View File

@@ -23,6 +23,7 @@
npm-debug.log*
yarn-debug.log*
yarn-error.log*
.yarn
# local env files
.env.local

View File

@@ -94,7 +94,7 @@ const DeployEditor = () => {
}}
>
{`You haven't compiled any files yet, compile files on `}
<NextLink shallow href={`/develop/${router.query.slug}`} passHref>
<NextLink legacyBehavior shallow href={`/develop/${router.query.slug}`} passHref>
<Link as="a">develop view</Link>
</NextLink>
</Text>

View File

@@ -155,9 +155,11 @@ const EditorNavigation = ({ renderNav }: { renderNav?: () => ReactNode }) => {
>
<Image
src={session?.user?.image || ''}
width="30px"
height="30px"
objectFit="cover"
width="30"
height="30"
style={{
objectFit: 'cover'
}}
alt="User avatar"
/>
</Box>

View File

@@ -40,7 +40,6 @@ const EnrichLog: FC<EnrichLogProps> = ({ str }) => {
if (match.startsWith('HookSet')) {
const code = match.match(/^HookSet\((\d+)\)/)?.[1]
const val = hookSetCodes.find(v => code && v.code === +code)
console.log({ code, val })
if (!val) return match
const content = capitalize(val.description) || 'No hint available!'

View File

@@ -94,6 +94,14 @@ const setMarkers = (monacoE: typeof monaco) => {
})
}
const langWarnings: Record<string, { shown: boolean; message: string }> = {
ts: {
shown: false,
message:
'Typescript suppport for hooks is still in early planning stage, write actual hooks in C only for now!'
}
}
const HooksEditor = () => {
const editorRef = useRef<monaco.editor.IStandaloneCodeEditor>()
const monacoRef = useRef<typeof monaco>()
@@ -125,6 +133,14 @@ const HooksEditor = () => {
const file = snap.files[snap.active]
useEffect(() => {
let warning = langWarnings[file?.language || '']
if (warning && !warning.shown) {
alert(warning.message) // TODO Custom dialog.
warning.shown = true
}
}, [file])
const renderNav = () => (
<Tabs
label="File"
@@ -221,7 +237,7 @@ const HooksEditor = () => {
monaco.languages.register({
id: 'text',
extensions: ['.txt'],
mimetypes: ['text/plain'],
mimetypes: ['text/plain']
})
MonacoServices.install(monaco)
const webSocket = createWebSocket(
@@ -240,7 +256,7 @@ const HooksEditor = () => {
try {
disposable.dispose()
} catch (err) {
console.log('err', err)
console.error('err', err)
}
})
}

View File

@@ -160,7 +160,7 @@ export const Log: FC<ILog> = ({
)}
<Pre>{message}</Pre>
{link && (
<NextLink href={link} shallow passHref>
<NextLink legacyBehavior href={link} shallow passHref>
<Link as="a">{linkText}</Link>
</NextLink>
)}

View File

@@ -1,5 +1,5 @@
import React from 'react'
import Link from 'next/link'
import NextLink from 'next/link'
import { useSnapshot } from 'valtio'
import { useRouter } from 'next/router'
@@ -78,7 +78,7 @@ const Navigation = () => {
pr: '$4'
}}
>
<Link href={gistId ? `/develop/${gistId}` : '/develop'} passHref>
<NextLink legacyBehavior href={gistId ? `/develop/${gistId}` : '/develop'} passHref>
<Box
as="a"
css={{
@@ -89,7 +89,7 @@ const Navigation = () => {
>
<Logo width="32px" height="32px" />
</Box>
</Link>
</NextLink>
<Flex
css={{
ml: '$5',
@@ -105,7 +105,8 @@ const Navigation = () => {
<Text css={{ fontSize: '$xs', color: '$mauve10', lineHeight: 1 }}>
{snap.files.length > 0 ? 'Gist: ' : 'Builder'}
{snap.files.length > 0 && (
<Link
<NextLink
legacyBehavior
href={`https://gist.github.com/${snap.gistOwner || ''}/${snap.gistId || ''}`}
passHref
>
@@ -117,7 +118,7 @@ const Navigation = () => {
>
{`${snap.gistOwner || '-'}/${truncate(snap.gistId || '')}`}
</Text>
</Link>
</NextLink>
)}
</Text>
</>
@@ -336,29 +337,39 @@ const Navigation = () => {
}}
>
<ButtonGroup>
<Link href={gistId ? `/develop/${gistId}` : '/develop'} passHref shallow>
<NextLink
legacyBehavior
href={gistId ? `/develop/${gistId}` : '/develop'}
passHref
shallow
>
<Button as="a" outline={!router.pathname.includes('/develop')} uppercase>
Develop
</Button>
</Link>
<Link href={gistId ? `/deploy/${gistId}` : '/deploy'} passHref shallow>
</NextLink>
<NextLink
legacyBehavior
href={gistId ? `/deploy/${gistId}` : '/deploy'}
passHref
shallow
>
<Button as="a" outline={!router.pathname.includes('/deploy')} uppercase>
Deploy
</Button>
</Link>
<Link href={gistId ? `/test/${gistId}` : '/test'} passHref shallow>
</NextLink>
<NextLink legacyBehavior href={gistId ? `/test/${gistId}` : '/test'} passHref shallow>
<Button as="a" outline={!router.pathname.includes('/test')} uppercase>
Test
</Button>
</Link>
</NextLink>
</ButtonGroup>
<Link href="https://xrpl-hooks.readme.io/v2.0" passHref>
<NextLink legacyBehavior href="https://xrpl-hooks.readme.io/v2.0" passHref>
<a target="_blank" rel="noreferrer noopener">
<Button outline>
<BookOpen size="15px" />
</Button>
</a>
</Link>
</NextLink>
</Stack>
</Flex>
</Container>

View File

@@ -3,13 +3,11 @@ import { mauve, mauveDark, purple, purpleDark } from '@radix-ui/colors'
import { useTheme } from 'next-themes'
import { styled } from '../stitches.config'
import dynamic from 'next/dynamic'
import type { Props } from 'react-select'
import type { Props, StylesConfig } from 'react-select'
const SelectInput = dynamic(() => import('react-select'), { ssr: false })
const CreatableSelectInput = dynamic(() => import('react-select/creatable'), { ssr: false })
// eslint-disable-next-line react/display-name
const Select = forwardRef<any, Props>((props, ref) => {
const { theme } = useTheme()
const isDark = theme === 'dark'
const getColors = (isDark: boolean) => {
const colors: any = {
// primary: pink.pink9,
active: isDark ? purpleDark.purple9 : purple.purple9,
@@ -30,11 +28,12 @@ const Select = forwardRef<any, Props>((props, ref) => {
}
colors.outline = colors.background
colors.selected = colors.secondary
return (
<SelectInput
ref={ref}
menuPosition={props.menuPosition || 'fixed'}
styles={{
return colors
}
const getStyles = (isDark: boolean) => {
const colors = getColors(isDark)
const styles: StylesConfig = {
container: provided => {
return {
...provided,
@@ -108,16 +107,57 @@ const Select = forwardRef<any, Props>((props, ref) => {
dropdownIndicator: (provided, state) => {
return {
...provided,
padding: 6,
color: state.isFocused ? colors.border : colors.secondary,
':hover': {
color: colors.border
}
}
},
clearIndicator: provided => {
return {
...provided,
padding: 6,
color: colors.secondary,
':hover': {
color: colors.border
}
}}
}
}
}
return styles
}
// eslint-disable-next-line react/display-name
const Select = forwardRef<any, Props>((props, ref) => {
const { theme } = useTheme()
const isDark = theme === 'dark'
const styles = getStyles(isDark)
return (
<SelectInput
ref={ref}
menuPosition={props.menuPosition || 'fixed'}
styles={styles}
{...props}
/>
)
})
// eslint-disable-next-line react/display-name
const Creatable = forwardRef<any, Props>((props, ref) => {
const { theme } = useTheme()
const isDark = theme === 'dark'
const styles = getStyles(isDark)
return (
<CreatableSelectInput
ref={ref}
formatCreateLabel={label => `Enter "${label}"`}
menuPosition={props.menuPosition || 'fixed'}
styles={styles}
{...props}
/>
)
})
export default styled(Select, {})
export const CreatableSelect = styled(Creatable, {})

71
components/Sequence.tsx Normal file
View File

@@ -0,0 +1,71 @@
import { FC, useCallback, useState } from 'react'
import state from '../state'
import { Flex, Input, Button } from '.'
import fetchAccountInfo from '../utils/accountInfo'
import { useSnapshot } from 'valtio'
interface AccountSequenceProps {
address?: string
}
const AccountSequence: FC<AccountSequenceProps> = ({ address }) => {
const { accounts } = useSnapshot(state)
const account = accounts.find(acc => acc.address === address)
const [isLoading, setIsLoading] = useState(false)
const setSequence = useCallback(
(sequence: number) => {
const acc = state.accounts.find(acc => acc.address == address)
if (!acc) return
acc.sequence = sequence
},
[address]
)
const handleUpdateSequence = useCallback(
async (silent?: boolean) => {
if (!account) return
setIsLoading(true)
const info = await fetchAccountInfo(account.address, { silent })
if (info) {
setSequence(info.Sequence)
}
setIsLoading(false)
},
[account, setSequence]
)
const disabled = !account
return (
<Flex row align="center" fluid>
<Input
placeholder="Account sequence"
value={account?.sequence || ""}
disabled={!account}
type="number"
readOnly={true}
/>
<Button
size="xs"
variant="primary"
type="button"
outline
disabled={disabled}
isDisabled={disabled}
isLoading={isLoading}
css={{
background: '$backgroundAlt',
position: 'absolute',
right: '$2',
fontSize: '$xs',
cursor: 'pointer',
alignContent: 'center',
display: 'flex'
}}
onClick={() => handleUpdateSequence()}
>
Update
</Button>
</Flex>
)
}
export default AccountSequence

View File

@@ -21,6 +21,7 @@ import { prepareDeployHookTx, sha256 } from '../state/actions/deployHook'
import estimateFee from '../utils/estimateFee'
import { getParameters, getInvokeOptions, transactionOptions, SetHookData } from '../utils/setHook'
import { capitalize } from '../utils/helpers'
import AccountSequence from './Sequence'
export const SetHookDialog: React.FC<{ accountAddress: string }> = React.memo(
({ accountAddress }) => {
@@ -190,6 +191,10 @@ export const SetHookDialog: React.FC<{ accountAddress: string }> = React.memo(
onChange={(acc: any) => setSelectedAccount(acc)}
/>
</Box>
<Box css={{ width: '100%', position: 'relative' }}>
<Label>Sequence</Label>
<AccountSequence address={selectedAccount?.value} />
</Box>
<Box css={{ width: '100%' }}>
<Label>Invoke on transactions</Label>
<Controller

View File

@@ -43,32 +43,38 @@ const Transaction: FC<TransactionProps> = ({ header, state: txState, ...props })
(state: Partial<TransactionState> = txState) => {
const {
selectedTransaction,
selectedDestAccount,
selectedAccount,
txFields,
selectedFlags,
hookParameters
hookParameters,
memos
} = state
const TransactionType = selectedTransaction?.value || null
const Destination = selectedDestAccount?.value || txFields?.Destination
const Account = selectedAccount?.value || null
const Flags = combineFlags(selectedFlags?.map(flag => flag.value)) || txFields?.Flags
const HookParameters = Object.entries(hookParameters || {}).reduce<
SetHookData['HookParameters']
>((acc, [_, { label, value }]) => {
return acc.concat({
HookParameter: { HookParameterName: toHex(label), HookParameterValue: toHex(value) }
HookParameter: { HookParameterName: toHex(label), HookParameterValue: value }
})
}, [])
const Memos = memos
? Object.entries(memos).reduce<SetHookData['Memos']>((acc, [_, { format, data, type }]) => {
return acc?.concat({
Memo: { MemoData: data, MemoFormat: toHex(format), MemoType: toHex(type) }
})
}, [])
: undefined
return prepareTransaction({
...txFields,
HookParameters,
Flags,
TransactionType,
Destination,
Account
Account,
Memos
})
},
[txState]
@@ -84,15 +90,29 @@ const Transaction: FC<TransactionProps> = ({ header, state: txState, ...props })
}
}, [selectedAccount?.value, selectedTransaction?.value, setState, txIsLoading])
const getJsonString = useCallback(
(state?: Partial<TransactionState>) =>
JSON.stringify(prepareOptions?.(state) || {}, null, editorSettings.tabSize),
[editorSettings.tabSize, prepareOptions]
)
const saveEditorState = useCallback(
(value: string = '', transactionType?: string) => {
const pTx = prepareState(value, transactionType)
if (pTx) {
pTx.editorValue = getJsonString(pTx)
return setState(pTx)
}
},
[getJsonString, setState]
)
const submitTest = useCallback(async () => {
let st: TransactionState | undefined
const tt = txState.selectedTransaction?.value
if (viewType === 'json') {
// save the editor state first
const pst = prepareState(editorValue || '', tt)
if (!pst) return
st = setState(pst)
st = saveEditorState(editorValue, tt)
if (!st) return
}
const account = accounts.find(acc => acc.address === selectedAccount?.value)
@@ -105,11 +125,12 @@ const Transaction: FC<TransactionProps> = ({ header, state: txState, ...props })
throw Error('Account must be selected from imported accounts!')
}
const options = prepareOptions(st)
const fields = getTxFields(options.TransactionType)
if (fields.Destination && !options.Destination) {
throw Error('Destination account is required!')
// delete unnecessary fields
Object.keys(options).forEach(field => {
if (!options[field]) {
delete options[field]
}
})
await sendTransaction(account, options, { logPrefix })
} catch (error) {
@@ -123,23 +144,18 @@ const Transaction: FC<TransactionProps> = ({ header, state: txState, ...props })
}
setState({ txIsLoading: false })
}, [
txState.selectedTransaction?.value,
viewType,
accounts,
txIsDisabled,
setState,
header,
saveEditorState,
editorValue,
txState,
selectedAccount?.value,
prepareOptions
])
const getJsonString = useCallback(
(state?: Partial<TransactionState>) =>
JSON.stringify(prepareOptions?.(state) || {}, null, editorSettings.tabSize),
[editorSettings.tabSize, prepareOptions]
)
const resetState = useCallback(
(transactionType: SelectOption | undefined = defaultTransactionType) => {
const fields = getTxFields(transactionType?.value)
@@ -149,13 +165,6 @@ const Transaction: FC<TransactionProps> = ({ header, state: txState, ...props })
selectedTransaction: transactionType
}
if (fields.Destination !== undefined) {
nwState.selectedDestAccount = null
fields.Destination = ''
} else {
fields.Destination = undefined
}
if (transactionType?.value && transactionFlags[transactionType?.value] && fields.Flags) {
nwState.selectedFlags = extractFlags(transactionType.value, fields.Flags)
fields.Flags = undefined
@@ -192,11 +201,21 @@ const Transaction: FC<TransactionProps> = ({ header, state: txState, ...props })
[accounts, prepareOptions, setState, txState]
)
const switchToJson = useCallback(() => {
const editorValue = getJsonString()
setState({ viewType: 'json', editorValue })
}, [getJsonString, setState])
const switchToUI = useCallback(() => {
setState({ viewType: 'ui' })
}, [setState])
return (
<Box css={{ position: 'relative', height: 'calc(100% - 28px)' }} {...props}>
{viewType === 'json' ? (
<TxJson
getJsonString={getJsonString}
saveEditorState={saveEditorState}
header={header}
state={txState}
setState={setState}
@@ -204,6 +223,7 @@ const Transaction: FC<TransactionProps> = ({ header, state: txState, ...props })
/>
) : (
<TxUI
switchToJson={switchToJson}
state={txState}
resetState={resetState}
setState={setState}
@@ -224,8 +244,8 @@ const Transaction: FC<TransactionProps> = ({ header, state: txState, ...props })
<Button
onClick={() => {
if (viewType === 'ui') {
setState({ viewType: 'json' })
} else setState({ viewType: 'ui' })
switchToJson()
} else switchToUI()
}}
outline
>

View File

@@ -1,6 +1,6 @@
import { FC, useCallback, useEffect, useMemo, useState } from 'react'
import { FC, useCallback, useEffect, useState } from 'react'
import { useSnapshot } from 'valtio'
import state, { prepareState, transactionsData, TransactionState } from '../../state'
import state, { transactionsData, TransactionState } from '../../state'
import Text from '../Text'
import { Flex, Link } from '..'
import { showAlert } from '../../state/actions/showAlert'
@@ -11,27 +11,27 @@ import Monaco from '../Monaco'
import type monaco from 'monaco-editor'
interface JsonProps {
getJsonString?: (state?: Partial<TransactionState>) => string
getJsonString: (st?: Partial<TransactionState>) => string
saveEditorState: (val?: string, tt?: string) => TransactionState | undefined
header?: string
setState: (pTx?: Partial<TransactionState> | undefined) => void
state: TransactionState
estimateFee?: () => Promise<string | undefined>
}
export const TxJson: FC<JsonProps> = ({ getJsonString, state: txState, header, setState }) => {
export const TxJson: FC<JsonProps> = ({
getJsonString,
state: txState,
header,
setState,
saveEditorState
}) => {
const { editorSettings, accounts } = useSnapshot(state)
const { editorValue, estimatedFee } = txState
const { editorValue, estimatedFee, editorIsSaved } = txState
const [currTxType, setCurrTxType] = useState<string | undefined>(
txState.selectedTransaction?.value
)
useEffect(() => {
setState({
editorValue: getJsonString?.()
})
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [])
useEffect(() => {
const parsed = parseJSON(editorValue)
if (!parsed) return
@@ -44,29 +44,19 @@ export const TxJson: FC<JsonProps> = ({ getJsonString, state: txState, header, s
}
}, [editorValue])
const saveState = (value: string, transactionType?: string) => {
const tx = prepareState(value, transactionType)
if (tx) {
setState(tx)
setState({
editorValue: getJsonString?.(tx)
})
}
}
const discardChanges = () => {
showAlert('Confirm', {
body: 'Are you sure to discard these changes?',
confirmText: 'Yes',
onCancel: () => {},
onConfirm: () => setState({ editorValue: getJsonString?.() })
onConfirm: () => setState({ editorValue: getJsonString() })
})
}
const onExit = (value: string) => {
const options = parseJSON(value)
if (options) {
saveState(value, currTxType)
saveEditorState(value, currTxType)
return
}
showAlert('Error!', {
@@ -163,8 +153,6 @@ export const TxJson: FC<JsonProps> = ({ getJsonString, state: txState, header, s
})
}, [getSchemas, monacoInst])
const hasUnsaved = useMemo(() => editorValue !== getJsonString?.(), [editorValue, getJsonString])
return (
<Monaco
rootProps={{
@@ -174,7 +162,7 @@ export const TxJson: FC<JsonProps> = ({ getJsonString, state: txState, header, s
id={header}
height="100%"
value={editorValue}
onChange={val => setState({ editorValue: val })}
onChange={val => setState({ editorValue: val, editorIsSaved: false })}
onMount={(editor, monaco) => {
editor.updateOptions({
minimap: { enabled: false },
@@ -190,12 +178,12 @@ export const TxJson: FC<JsonProps> = ({ getJsonString, state: txState, header, s
model?.onWillDispose(() => onExit(model.getValue()))
}}
overlay={
hasUnsaved ? (
!editorIsSaved ? (
<Flex row align="center" css={{ fontSize: '$xs', color: '$textMuted', ml: 'auto' }}>
<Text muted small>
This file has unsaved changes.
</Text>
<Link css={{ ml: '$1' }} onClick={() => saveState(editorValue || '', currTxType)}>
<Link css={{ ml: '$1' }} onClick={() => saveEditorState(editorValue, currTxType)}>
save
</Link>
<Link css={{ ml: '$1' }} onClick={discardChanges}>

View File

@@ -1,55 +1,50 @@
import { FC, ReactNode, useCallback, useEffect, useMemo, useState } from 'react'
import { FC, ReactNode, useCallback, useEffect, useState } from 'react'
import Container from '../Container'
import Flex from '../Flex'
import Input from '../Input'
import Select from '../Select'
import Select, { CreatableSelect } from '../Select'
import Text from '../Text'
import {
SelectOption,
TransactionState,
transactionsOptions,
TxFields,
getTxFields,
defaultTransactionType
} from '../../state/transactions'
import { useSnapshot } from 'valtio'
import state from '../../state'
import { streamState } from '../DebugStream'
import { Button } from '..'
import { Box, Button } from '..'
import Textarea from '../Textarea'
import { getFlags } from '../../state/constants/flags'
import { Plus, Trash } from 'phosphor-react'
import AccountSequence from '../Sequence'
import { capitalize, typeIs } from '../../utils/helpers'
interface UIProps {
setState: (pTx?: Partial<TransactionState> | undefined) => TransactionState | undefined
resetState: (tt?: SelectOption) => TransactionState | undefined
state: TransactionState
estimateFee?: (...arg: any) => Promise<string | undefined>
switchToJson: () => void
}
export const TxUI: FC<UIProps> = ({ state: txState, setState, resetState, estimateFee }) => {
export const TxUI: FC<UIProps> = ({
state: txState,
setState,
resetState,
estimateFee,
switchToJson
}) => {
const { accounts } = useSnapshot(state)
const {
selectedAccount,
selectedDestAccount,
selectedTransaction,
txFields,
selectedFlags,
hookParameters
} = txState
const { selectedAccount, selectedTransaction, txFields, selectedFlags, hookParameters, memos } =
txState
const accountOptions: SelectOption[] = accounts.map(acc => ({
label: acc.name,
value: acc.address
}))
const destAccountOptions: SelectOption[] = accounts
.map(acc => ({
label: acc.name,
value: acc.address
}))
.filter(acc => acc.value !== selectedAccount?.value)
const flagsOptions: SelectOption[] = Object.entries(
getFlags(selectedTransaction?.value) || {}
).map(([label, value]) => ({
@@ -78,6 +73,22 @@ export const TxUI: FC<UIProps> = ({ state: txState, setState, resetState, estima
[setState, txFields]
)
const setRawField = useCallback(
(field: keyof TxFields, type: string, value: any) => {
// TODO $type should be a narrowed type
setState({
txFields: {
...txFields,
[field]: {
$type: type,
$value: value
}
}
})
},
[setState, txFields]
)
const handleEstimateFee = useCallback(
async (state?: TransactionState, silent?: boolean) => {
setFeeLoading(true)
@@ -101,8 +112,6 @@ export const TxUI: FC<UIProps> = ({ state: txState, setState, resetState, estima
[handleEstimateFee, resetState, setState]
)
const switchToJson = () => setState({ viewType: 'json' })
// default tx
useEffect(() => {
if (selectedTransaction?.value) return
@@ -112,21 +121,23 @@ export const TxUI: FC<UIProps> = ({ state: txState, setState, resetState, estima
}
}, [handleChangeTxType, selectedTransaction?.value])
const fields = useMemo(
() => getTxFields(selectedTransaction?.value),
[selectedTransaction?.value]
)
const richFields = ['TransactionType', 'Account', 'HookParameters']
if (fields.Destination !== undefined) {
richFields.push('Destination')
}
const richFields = ['TransactionType', 'Account', 'HookParameters', 'Memos']
if (flagsOptions.length) {
richFields.push('Flags')
}
const otherFields = Object.keys(txFields).filter(k => !richFields.includes(k)) as [keyof TxFields]
const amountOptions = [
{ label: 'XRP', value: 'xrp' },
{ label: 'Token', value: 'token' }
] as const
const defaultTokenAmount = {
value: '0',
currency: '',
issuer: ''
}
return (
<Container
css={{
@@ -155,18 +166,9 @@ export const TxUI: FC<UIProps> = ({ state: txState, setState, resetState, estima
onChange={(acc: any) => handleSetAccount(acc)} // TODO make react-select have correct types for acc
/>
</TxField>
{richFields.includes('Destination') && (
<TxField label="Destination account">
<Select
instanceId="to-account"
placeholder="Select the destination account"
options={destAccountOptions}
value={selectedDestAccount}
isClearable
onChange={(acc: any) => setState({ selectedDestAccount: acc })}
/>
<TxField label="Sequence">
<AccountSequence address={selectedAccount?.value} />
</TxField>
)}
{richFields.includes('Flags') && (
<TxField label="Flags">
<Select
@@ -188,23 +190,133 @@ export const TxUI: FC<UIProps> = ({ state: txState, setState, resetState, estima
let _value = txFields[field]
let value: string | undefined
if (typeof _value === 'object') {
if (_value.$type === 'json' && typeof _value.$value === 'object') {
if (typeIs(_value, 'object')) {
if (_value.$type === 'json' && typeIs(_value.$value, ['object', 'array'])) {
value = JSON.stringify(_value.$value, null, 2)
} else {
value = _value.$value.toString()
value = _value.$value?.toString()
}
} else {
value = _value?.toString()
}
const isXrp = typeof _value === 'object' && _value.$type === 'xrp'
const isAccount = typeIs(_value, 'object') && _value.$type === 'account'
const isXrpAmount = typeIs(_value, 'object') && _value.$type === 'amount.xrp'
const isTokenAmount = typeIs(_value, 'object') && _value.$type === 'amount.token'
const isJson = typeof _value === 'object' && _value.$type === 'json'
const isFee = field === 'Fee'
let rows = isJson ? (value?.match(/\n/gm)?.length || 0) + 1 : undefined
if (rows && rows > 5) rows = 5
let tokenAmount = defaultTokenAmount
if (isTokenAmount && typeIs(_value, 'object') && typeIs(_value.$value, 'object')) {
tokenAmount = {
value: _value.$value.value,
currency: _value.$value.currency,
issuer: _value.$value.issuer
}
}
if (isXrpAmount || isTokenAmount) {
return (
<TxField key={field} label={field + (isXrp ? ' (XRP)' : '')}>
<TxField key={field} label={field}>
<Flex fluid css={{ alignItems: 'center' }}>
{isTokenAmount ? (
<Flex
fluid
row
align="center"
justify="space-between"
css={{ position: 'relative' }}
>
{/* <Input
type="text"
placeholder="Issuer"
value={tokenAmount.issuer}
onChange={e =>
setRawField(field, 'amount.token', {
...tokenAmount,
issuer: e.target.value
})
}
/> */}
<Input
type="text"
value={tokenAmount.currency}
placeholder="Currency"
onChange={e => {
setRawField(field, 'amount.token', {
...tokenAmount,
currency: e.target.value
})
}}
/>
<Input
css={{ mx: '$1' }}
type="number"
value={tokenAmount.value}
placeholder="Value"
onChange={e => {
setRawField(field, 'amount.token', {
...tokenAmount,
value: e.target.value
})
}}
/>
<Box css={{ width: '50%' }}>
<CreatableAccount
value={tokenAmount.issuer}
field={'Issuer' as any}
placeholder="Issuer"
setField={(_, value = '') => {
setRawField(field, 'amount.token', {
...tokenAmount,
issuer: value
})
}}
/>
</Box>
</Flex>
) : (
<Input
css={{ flex: 'inherit' }}
type="number"
value={value}
onChange={e => handleSetField(field, e.target.value)}
/>
)}
<Box
css={{
ml: '$2',
width: '150px'
}}
>
<Select
instanceId="currency-type"
options={amountOptions}
value={isXrpAmount ? amountOptions['0'] : amountOptions['1']}
onChange={(e: any) => {
const opt = e as typeof amountOptions[number]
if (opt.value === 'xrp') {
setRawField(field, 'amount.xrp', '0')
} else {
setRawField(field, 'amount.token', defaultTokenAmount)
}
}}
/>
</Box>
</Flex>
</TxField>
)
}
if (isAccount) {
return (
<TxField key={field} label={field}>
<CreatableAccount value={value} field={field} setField={handleSetField} />
</TxField>
)
}
return (
<TxField key={field} label={field}>
{isJson ? (
<Textarea
rows={rows}
@@ -294,7 +406,7 @@ export const TxUI: FC<UIProps> = ({ state: txState, setState, resetState, estima
/>
<Input
css={{ mx: '$2' }}
placeholder="Value"
placeholder="Value (hex-quoted)"
value={value}
onChange={e => {
setState({
@@ -333,11 +445,117 @@ export const TxUI: FC<UIProps> = ({ state: txState, setState, resetState, estima
</Button>
</Flex>
</TxField>
<TxField multiLine label="Memos">
<Flex column fluid>
{Object.entries(memos).map(([id, memo]) => (
<Flex column key={id} css={{ mb: '$2' }}>
<Flex
row
css={{
flexWrap: 'wrap',
width: '100%'
}}
>
<Input
placeholder="Memo type"
value={memo.type}
onChange={e => {
setState({
memos: {
...memos,
[id]: { ...memo, type: e.target.value }
}
})
}}
/>
<Input
placeholder="Data (hex-quoted)"
css={{ mx: '$2' }}
value={memo.data}
onChange={e => {
setState({
memos: {
...memos,
[id]: { ...memo, data: e.target.value }
}
})
}}
/>
<Input
placeholder="Format"
value={memo.format}
onChange={e => {
setState({
memos: {
...memos,
[id]: { ...memo, format: e.target.value }
}
})
}}
/>
<Button
css={{ ml: '$2' }}
onClick={() => {
const { [id]: _, ...rest } = memos
setState({ memos: rest })
}}
variant="destroy"
>
<Trash weight="regular" size="16px" />
</Button>
</Flex>
</Flex>
))}
<Button
outline
fullWidth
type="button"
onClick={() => {
const id = Object.keys(memos).length
setState({
memos: { ...memos, [id]: { data: '', format: '', type: '' } }
})
}}
>
<Plus size="16px" />
Add Memo
</Button>
</Flex>
</TxField>
</Flex>
</Container>
)
}
export const CreatableAccount: FC<{
value: string | undefined
field: keyof TxFields
placeholder?: string
setField: (field: keyof TxFields, value: string, opFields?: TxFields) => void
}> = ({ value, field, setField, placeholder }) => {
const { accounts } = useSnapshot(state)
const accountOptions: SelectOption[] = accounts.map(acc => ({
label: acc.name,
value: acc.address
}))
const label = accountOptions.find(a => a.value === value)?.label || value
const val = {
value,
label
}
placeholder = placeholder || `${capitalize(field)} account`
return (
<CreatableSelect
isClearable
instanceId={field}
placeholder={placeholder}
options={accountOptions}
value={value ? val : undefined}
onChange={(acc: any) => setField(field, acc?.value)}
/>
)
}
export const TxField: FC<{ label: string; children: ReactNode; multiLine?: boolean }> = ({
label,
children,
@@ -351,7 +569,7 @@ export const TxField: FC<{ label: string; children: ReactNode; multiLine?: boole
justifyContent: 'flex-end',
alignItems: multiLine ? 'flex-start' : 'center',
position: 'relative',
mb: '$3',
mb: '$2',
mt: '1px',
pr: '1px'
}}

View File

@@ -2,7 +2,10 @@
{
"TransactionType": "AccountDelete",
"Account": "rWYkbWkCeg8dP6rXALnjgZSjjLyih5NXm",
"Destination": "rPT1Sjq2YGrBMTttX4GZHjKu9dyfzbpAYe",
"Destination": {
"$type": "account",
"$value": ""
},
"DestinationTag": 13,
"Fee": "2000000",
"Sequence": 2470665,
@@ -28,7 +31,11 @@
"TransactionType": "CheckCash",
"Amount": {
"$value": "100",
"$type": "xrp"
"$type": "amount.xrp"
},
"DeliverMin": {
"$value": "",
"$type": "amount.xrp"
},
"CheckID": "838766BA2B995C00744175F69A1B11E32C3DBC40E64801A4056FCBD657F57334",
"Fee": "12"
@@ -36,7 +43,10 @@
{
"TransactionType": "CheckCreate",
"Account": "rUn84CUYbNjRoTQ6mSW7BVJPSVJNLb1QLo",
"Destination": "rfkE1aSy9G8Upk4JssnwBxhEv5p4mn2KTy",
"Destination": {
"$type": "account",
"$value": ""
},
"SendMax": "100000000",
"Expiration": 570113521,
"InvoiceID": "6F1DFD1D0FE8A32E40E1F2C05CF1C15545BAB56B617F9C6C2D63A6B704BEF59B",
@@ -54,7 +64,10 @@
{
"Account": "rf1BiGeXwwQoi8Z2ueFYTEXSwuJYfV2Jpn",
"TransactionType": "EscrowCancel",
"Owner": "rf1BiGeXwwQoi8Z2ueFYTEXSwuJYfV2Jpn",
"Owner": {
"$type": "account",
"$value": ""
},
"OfferSequence": 7,
"Fee": "10"
},
@@ -63,9 +76,12 @@
"TransactionType": "EscrowCreate",
"Amount": {
"$value": "100",
"$type": "xrp"
"$type": "amount.xrp"
},
"Destination": {
"$type": "account",
"$value": ""
},
"Destination": "rsA2LpzuawewSBQXkiju3YQTMzW13pAAdW",
"CancelAfter": 533257958,
"FinishAfter": 533171558,
"Condition": "A0258020E3B0C44298FC1C149AFBF4C8996FB92427AE41E4649B934CA495991B7852B855810100",
@@ -76,7 +92,10 @@
{
"Account": "rf1BiGeXwwQoi8Z2ueFYTEXSwuJYfV2Jpn",
"TransactionType": "EscrowFinish",
"Owner": "rf1BiGeXwwQoi8Z2ueFYTEXSwuJYfV2Jpn",
"Owner": {
"$type": "account",
"$value": ""
},
"OfferSequence": 7,
"Condition": "A0258020E3B0C44298FC1C149AFBF4C8996FB92427AE41E4649B934CA495991B7852B855810100",
"Fulfillment": "A0028000",
@@ -120,10 +139,17 @@
"NFTokenID": "000100001E962F495F07A990F4ED55ACCFEEF365DBAA76B6A048C0A200000007",
"Amount": {
"$value": "100",
"$type": "xrp"
"$type": "amount.xrp"
},
"Flags": "1",
"Destination": "",
"Destination": {
"$type": "account",
"$value": ""
},
"Owner": {
"$type": "account",
"$value": ""
},
"Fee": "10"
},
{
@@ -142,19 +168,29 @@
"Flags": "0",
"LastLedgerSequence": 7108682,
"Sequence": 8,
"TakerGets": "6000000",
"Amount": {
"$value": "100",
"$type": "xrp"
"TakerGets": {
"$type": "amount.xrp",
"$value": "6000000"
},
"TakerPays": {
"$type": "amount.token",
"$value": {
"currency": "GKO",
"issuer": "ruazs5h1qEsqpke88pcqnaseXdm6od2xc",
"value": "2"
}
}
},
{
"TransactionType": "Payment",
"Account": "rf1BiGeXwwQoi8Z2ueFYTEXSwuJYfV2Jpn",
"Destination": "ra5nK24KXen9AHvsdFTKHSANinZseWnPcX",
"Destination": {
"$type": "account",
"$value": ""
},
"Amount": {
"$value": "100",
"$type": "xrp"
"$type": "amount.xrp"
},
"Fee": "12",
"Flags": "2147483648",
@@ -165,9 +201,12 @@
"TransactionType": "PaymentChannelCreate",
"Amount": {
"$value": "100",
"$type": "xrp"
"$type": "amount.xrp"
},
"Destination": {
"$type": "account",
"$value": ""
},
"Destination": "rsA2LpzuawewSBQXkiju3YQTMzW13pAAdW",
"SettleDelay": 86400,
"PublicKey": "32D2471DB72B27E3310F355BB33E339BF26F8392D5A93D3BC0FC3B566612DA0F0A",
"CancelAfter": 533171558,
@@ -181,7 +220,7 @@
"Channel": "C1AE6DDDEEC05CF2978C0BAD6FE302948E9533691DC749DCDD3B9E5992CA6198",
"Amount": {
"$value": "200",
"$type": "xrp"
"$type": "amount.xrp"
},
"Expiration": 543171558,
"Fee": "10"
@@ -237,7 +276,7 @@
"Flags": "262144",
"LastLedgerSequence": 8007750,
"LimitAmount": {
"$type": "json",
"$type": "amount.token",
"$value": {
"currency": "USD",
"issuer": "rsP3mgGb2tcYUrxiLFiHJiQXhsziegtwBc",
@@ -248,6 +287,10 @@
},
{
"TransactionType": "Invoke",
"Destination": {
"$type": "account",
"$value": ""
},
"Fee": "12"
},
{

View File

@@ -1,7 +1,7 @@
import type { NextRequest, NextFetchEvent } from 'next/server'
import type { NextRequest } from 'next/server'
import { NextResponse as Response } from 'next/server'
export default function middleware(req: NextRequest, ev: NextFetchEvent) {
export default function middleware(req: NextRequest) {
if (req.nextUrl.pathname === '/') {
const url = req.nextUrl.clone()
url.pathname = '/develop'

View File

@@ -8,8 +8,16 @@ module.exports = {
config.resolve.alias['vscode'] = require.resolve(
'@codingame/monaco-languageclient/lib/vscode-compatibility'
)
config.experiments = {
topLevelAwait: true,
layers: true
}
if (!isServer) {
config.resolve.fallback.fs = false
config.resolve.fallback = {
...config.resolve.fallback,
fs: false,
module: false
}
}
config.module.rules.push({
test: [/\.md$/, /hook-bundle\.js$/],

View File

@@ -14,6 +14,7 @@
"dependencies": {
"@codingame/monaco-jsonrpc": "^0.3.1",
"@codingame/monaco-languageclient": "^0.17.0",
"@eqlabs/assemblyscript": "^0.0.0-alpha.1680097351",
"@monaco-editor/react": "^4.4.5",
"@octokit/core": "^3.5.1",
"@radix-ui/colors": "^0.1.7",
@@ -37,7 +38,7 @@
"lodash.uniqby": "^4.7.0",
"lodash.xor": "^4.5.0",
"monaco-editor": "^0.33.0",
"next": "^12.0.4",
"next": "^13.1.1",
"next-auth": "^4.10.3",
"next-plausible": "^3.2.0",
"next-themes": "^0.1.1",
@@ -49,8 +50,8 @@
"postinstall-postinstall": "^2.1.0",
"prettier": "^2.7.1",
"re-resizable": "^6.9.1",
"react": "17.0.2",
"react-dom": "17.0.2",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-hook-form": "^7.28.0",
"react-hot-keys": "^2.7.1",
"react-hot-toast": "^2.1.1",
@@ -65,7 +66,7 @@
"valtio": "^1.2.5",
"vscode-languageserver": "^7.0.0",
"vscode-uri": "^3.0.2",
"wabt": "^1.0.30",
"wabt": "^1.0.32",
"xrpl-accountlib": "^1.6.1",
"xrpl-client": "^2.0.2"
},
@@ -78,7 +79,7 @@
"@types/react": "17.0.31",
"browserify": "^17.0.0",
"eslint": "7.32.0",
"eslint-config-next": "11.1.2",
"eslint-config-next": "^13.1.1",
"raw-loader": "^4.0.2",
"typescript": "4.4.4"
},

View File

@@ -24,7 +24,7 @@ import { ChatCircleText } from 'phosphor-react'
TimeAgo.setDefaultLocale(en.locale)
TimeAgo.addLocale(en)
function MyApp({ Component, pageProps: { session, ...pageProps } }: AppProps) {
function MyApp({ Component, pageProps: { session, ...pageProps } }: AppProps<{ session?: any }>) {
const router = useRouter()
const slug = router.query?.slug
const gistId = (Array.isArray(slug) && slug[0]) ?? null

View File

@@ -40,7 +40,7 @@ export default async function handler(
}
return res.status(200).json(json)
} catch (err) {
console.log(err)
console.error(err)
return res.status(500).json({ error: 'Server error' })
}
return res.status(500).json({ error: 'Not able to create faucet, try again' })

View File

@@ -150,7 +150,9 @@ const Home: NextPage = () => {
const activeFile = snap.files[snap.active] as IFile | undefined
const activeFileExt = getFileExtention(activeFile?.name)
const canCompile = activeFileExt === 'c' || activeFileExt === 'wat'
const canCompile = activeFileExt === 'c' || activeFileExt === 'wat' || activeFileExt === 'ts'
const isCompiling = snap.compiling.includes(snap.active);
return (
<Split
direction="vertical"
@@ -166,7 +168,9 @@ const Home: NextPage = () => {
{canCompile && (
<Hotkeys
keyName="command+b,ctrl+b"
onKeyDown={() => !snap.compiling && snap.files.length && compileCode(snap.active)}
onKeyDown={() =>
snap.compiling === undefined && snap.files.length && compileCode(snap.active)
}
>
<Flex
css={{
@@ -183,7 +187,7 @@ const Home: NextPage = () => {
variant="primary"
uppercase
disabled={!snap.files.length}
isLoading={snap.compiling}
isLoading={isCompiling}
onClick={() => compileCode(snap.active)}
>
<Play weight="bold" size="16px" />
@@ -200,7 +204,9 @@ const Home: NextPage = () => {
{activeFileExt === 'js' && (
<Hotkeys
keyName="command+b,ctrl+b"
onKeyDown={() => !snap.compiling && snap.files.length && compileCode(snap.active)}
onKeyDown={() =>
!isCompiling && snap.files.length && compileCode(snap.active)
}
>
<Flex
css={{

View File

@@ -1,5 +1,6 @@
import toast from 'react-hot-toast'
import state, { FaucetAccountRes } from '../index'
import fetchAccountInfo from '../../utils/accountInfo';
export const names = [
'Alice',
@@ -35,26 +36,23 @@ export const addFaucetAccount = async (name?: string, showToast: boolean = false
})
const json: FaucetAccountRes | { error: string } = await res.json()
if ('error' in json) {
if (showToast) {
if (!showToast) return;
return toast.error(json.error, { id: toastId })
} else {
return
}
} else {
if (showToast) {
toast.success('New account created', { id: toastId })
}
const currNames = state.accounts.map(acc => acc.name)
const info = await fetchAccountInfo(json.address, { silent: true })
state.accounts.push({
name: name || names.filter(name => !currNames.includes(name))[0],
xrp: (json.xrp || 0 * 1000000).toString(),
address: json.address,
secret: json.secret,
sequence: 1,
sequence: info?.Sequence || 1,
hooks: [],
isLoading: false,
version: '2'
})
if (showToast) {
toast.success('New account created', { id: toastId })
}
}

View File

@@ -1,40 +1,91 @@
import toast from 'react-hot-toast'
import Router from 'next/router'
import state from '../index'
import state, { IFile } from '../index'
import { saveFile } from './saveFile'
import { decodeBinary } from '../../utils/decodeBinary'
import { ref } from 'valtio'
import asc from "@eqlabs/assemblyscript/dist/asc"
import { getFileExtention } from '../../utils/helpers'
/* compileCode sends the code of the active file to compile endpoint
type CompilationResult = Pick<IFile, "compiledContent" | "compiledWatContent">
export const compileCode = async (activeId: number) => {
// Save the file to global state
saveFile(false, activeId)
const file = state.files[activeId]
// Bail out if we're already compiling the file.
if (!file || state.compiling.includes(activeId)) {
return
}
try {
state.compiling.push(activeId)
state.logs = []
file.containsErrors = false
let result: CompilationResult;
if (file.name.endsWith('.wat')) {
result = await compileWat(file);
}
else if (file.language === "ts") {
result = await compileTs(file);
}
else if (navigator?.onLine === false) {
throw Error('You seem offline, check you internet connection and try again!')
}
else if (file.language === 'c') {
result = await compileC(file)
}
else throw Error("Unknown file type.")
file.lastCompiled = new Date();
file.compiledValueSnapshot = file.content;
file.compiledContent = result.compiledContent;
file.compiledWatContent = result.compiledWatContent;
toast.success('Compiled successfully!', { position: 'bottom-center' })
state.logs.push({
type: 'success',
message: `File ${state.files?.[activeId]?.name} compiled successfully. Ready to deploy.`,
link: Router.asPath.replace('develop', 'deploy'),
linkText: 'Go to deploy'
})
} catch (err) {
console.error(err)
let message: string;
if (err instanceof Array && typeof err[0] === 'string') {
err.forEach(message => {
state.logs.push({
type: 'error',
message
})
})
message = "Compilation errors occurred, see logs for more info."
} else if (err instanceof Error) {
message = err.message
} else {
message = 'Something went wrong, try again later!'
}
toast.error(message, { position: 'bottom-center' })
file.containsErrors = true
}
state.compiling = state.compiling.filter(id => id !== activeId);
}
/* compileC sends the code of the active file to compile endpoint
* If all goes well you will get base64 encoded wasm file back with
* some extra logging information if we can provide it. This function
* also decodes the returned wasm and creates human readable WAT file
* out of it and store both in global state.
*/
export const compileCode = async (activeId: number) => {
// Save the file to global state
saveFile(false, activeId)
const file = state.files[activeId]
if (file.name.endsWith('.wat')) {
return compileWat(activeId)
}
export const compileC = async (file: IFile): Promise<CompilationResult> => {
if (!process.env.NEXT_PUBLIC_COMPILE_API_ENDPOINT) {
throw Error('Missing env!')
throw Error('Missing C compile endpoint!')
}
// Bail out if we're already compiling
if (state.compiling) {
// if compiling is ongoing return // TODO Inform user about it.
return
}
// Set loading state to true
state.compiling = true
state.logs = []
try {
file.containsErrors = false
let res: Response
try {
res = await fetch(process.env.NEXT_PUBLIC_COMPILE_API_ENDPOINT, {
method: 'POST',
headers: {
@@ -54,11 +105,8 @@ export const compileCode = async (activeId: number) => {
]
})
})
} catch (error) {
throw Error('Something went wrong, check your network connection and try again!')
}
const json = await res.json()
state.compiling = false
if (!json.success) {
const errors = [json.message]
if (json.tasks && json.tasks.length > 0) {
@@ -84,88 +132,87 @@ export const compileCode = async (activeId: number) => {
const wast = myModule.toText({ foldExprs: false, inlineExport: false })
file.compiledContent = ref(bufferData)
file.lastCompiled = new Date()
file.compiledValueSnapshot = file.content
file.compiledWatContent = wast
return {
compiledContent: ref(bufferData),
compiledWatContent: wast
}
} catch (error) {
throw Error('Invalid compilation result produced, check your code for errors and try again!')
}
toast.success('Compiled successfully!', { position: 'bottom-center' })
state.logs.push({
type: 'success',
message: `File ${state.files?.[activeId]?.name} compiled successfully. Ready to deploy.`,
link: Router.asPath.replace('develop', 'deploy'),
linkText: 'Go to deploy'
})
} catch (err) {
console.log(err)
if (err instanceof Array && typeof err[0] === 'string') {
err.forEach(message => {
state.logs.push({
type: 'error',
message
})
})
} else if (err instanceof Error) {
state.logs.push({
type: 'error',
message: err.message
})
} else {
state.logs.push({
type: 'error',
message: 'Something went wrong, come back later!'
})
}
state.compiling = false
toast.error(`Error occurred while compiling!`, { position: 'bottom-center' })
file.containsErrors = true
}
}
export const compileWat = async (activeId: number) => {
if (state.compiling) return;
const file = state.files[activeId]
state.compiling = true
state.logs = []
try {
export const compileWat = async (file: IFile): Promise<CompilationResult> => {
const wabt = await (await import('wabt')).default()
const module = wabt.parseWat(file.name, file.content);
module.resolveNames();
module.validate();
const { buffer } = module.toBinary({
const mod = wabt.parseWat(file.name, file.content);
mod.resolveNames();
mod.validate();
const { buffer } = mod.toBinary({
log: false,
write_debug_names: true,
});
file.compiledContent = ref(buffer)
file.lastCompiled = new Date()
file.compiledValueSnapshot = file.content
file.compiledWatContent = file.content
return {
compiledContent: ref(buffer),
compiledWatContent: file.content,
}
}
toast.success('Compiled successfully!', { position: 'bottom-center' })
export const compileTs = async (file: IFile): Promise<CompilationResult> => {
return new Promise(async (resolve, reject) => {
let result: Partial<CompilationResult> = {}
const { error, stdout, stderr } = await asc.main([
// Command line options
file.name,
"--outFile", `${file.name}.wasm`,
"--textFile", `${file.name}.wat`,
"--runtime", "stub",
"--initialMemory", "1",
"--maximumMemory", "1",
"--noExportMemory",
"--optimize",
"--topLevelToHook"
], {
readFile: (name, baseDir) => {
const file = state.files.find(file => file.name === name)
if (file) {
return file.content
}
return null
},
writeFile: async (name, data: ArrayBuffer | string, baseDir) => {
const ext = getFileExtention(name);
if (ext === 'wasm') {
result.compiledContent = data as ArrayBuffer;
}
else if (ext === 'wat') {
result.compiledWatContent = data as string;
}
if (result.compiledContent && result.compiledWatContent) {
resolve({ ...result });
}
},
listFiles: (dirname, baseDir) => {
return state.files.map(file => file.name)
},
// reportDiagnostic?: ...,
});
let logMsg = stdout.toString()
let errMsg = stderr.toString()
if (logMsg) {
state.logs.push({
type: 'success',
message: `File ${state.files?.[activeId]?.name} compiled successfully. Ready to deploy.`,
link: Router.asPath.replace('develop', 'deploy'),
linkText: 'Go to deploy'
type: "log",
message: logMsg
})
} catch (err) {
console.log(err)
let message = "Error compiling WAT file!"
if (err instanceof Error) {
message = err.message
}
if (errMsg) {
state.logs.push({
type: 'error',
message
type: "error",
message: errMsg
})
toast.error(`Error occurred while compiling!`, { position: 'bottom-center' })
file.containsErrors = true
}
state.compiling = false
if (error) return reject(error)
})
}

View File

@@ -1,8 +1,8 @@
import { getFileExtention } from '../../utils/helpers'
import state, { IFile } from '../index'
import state, { IFile, ILang } from '../index'
const languageMapping: Record<string, string | undefined> = {
ts: 'typescript',
const languageMapping: Record<string, ILang | undefined> = {
ts: 'ts',
js: 'javascript',
md: 'markdown',
c: 'c',

View File

@@ -14,11 +14,4 @@ export const deleteAccount = (addr?: string) => {
if (!acc) return
acc.label = acc.value
})
transactionsState.transactions
.filter(t => t.state.selectedDestAccount?.value === addr)
.forEach(t => {
const acc = t.state.selectedDestAccount
if (!acc) return
acc.label = acc.value
})
}

View File

@@ -247,7 +247,7 @@ export const deleteHook = async (account: IAccount & { name?: string }) => {
})
}
} catch (err) {
console.log(err)
console.error(err)
toast.error('Error occurred while deleting hook', { id: toastId })
state.deployLogs.push({
type: 'error',

View File

@@ -1,5 +1,5 @@
import { Octokit } from '@octokit/core'
import state, { IFile } from '../index'
import state, { IFile, ILang } from '../index'
import { templateFileIds } from '../constants'
const octokit = new Octokit()
@@ -48,7 +48,7 @@ export const fetchFiles = async (gistId: string) => {
const files: IFile[] = Object.keys(res.data.files).map(filename => ({
name: res.data.files?.[filename]?.filename || 'untitled.c',
language: res.data.files?.[filename]?.language?.toLowerCase() || '',
language: res.data.files?.[filename]?.language?.toLowerCase() as ILang | undefined,
content: res.data.files?.[filename]?.content || ''
}))

View File

@@ -10,7 +10,6 @@ interface TransactionOptions {
TransactionType: string
Account?: string
Fee?: string
Destination?: string
[index: string]: any
}
interface OtherOptions {

View File

@@ -55,7 +55,7 @@ export const syncToGist = async (session?: Session | null, createNewGist?: boole
return toast.success('Updated to gist successfully!', { id: toastId })
})
.catch(err => {
console.log(err)
console.error(err)
state.gistLoading = false
return toast.error(`Could not update Gist, try again later!`, {
id: toastId
@@ -85,7 +85,7 @@ export const syncToGist = async (session?: Session | null, createNewGist?: boole
return toast.success('Created new gist successfully!', { id: toastId })
})
.catch(err => {
console.log(err)
console.error(err)
state.gistLoading = false
return toast.error(`Could not create Gist, try again later!`, {
id: toastId

View File

@@ -9,9 +9,10 @@ declare module 'valtio' {
function snapshot<T extends object>(p: T): T
}
export type ILang = "ts" | "javascript" | "markdown" | "c" | "text"
export interface IFile {
name: string
language: string
language: ILang | undefined
content: string
compiledValueSnapshot?: string
compiledContent?: ArrayBuffer | null
@@ -66,7 +67,7 @@ export interface IState {
loading: boolean
gistLoading: boolean
zipLoading: boolean
compiling: boolean
compiling: /* file id */ number[]
logs: ILog[]
deployLogs: ILog[]
transactionLogs: ILog[]
@@ -98,7 +99,7 @@ let initialState: IState = {
// Active file index on the Deploy page editor
activeWat: 0,
loading: false,
compiling: false,
compiling: [],
logs: [],
deployLogs: [],
transactionLogs: [],
@@ -135,7 +136,7 @@ if (typeof window !== 'undefined') {
try {
localStorageAccounts = localStorage.getItem('hooksIdeAccounts')
} catch (err) {
console.log(`localStorage state broken`)
console.error(`localStorage state broken`)
localStorage.removeItem('hooksIdeAccounts')
}
if (localStorageAccounts) {

View File

@@ -6,6 +6,7 @@ import { showAlert } from '../state/actions/showAlert'
import { parseJSON } from '../utils/json'
import { extractFlags, getFlags } from './constants/flags'
import { fromHex } from '../utils/setHook'
import { typeIs } from '../utils/helpers'
export type SelectOption = {
value: string
@@ -16,17 +17,26 @@ export type HookParameters = {
[key: string]: SelectOption
}
export type Memos = {
[key: string]: {
type: string
format: string
data: string
}
}
export interface TransactionState {
selectedTransaction: SelectOption | null
selectedAccount: SelectOption | null
selectedDestAccount: SelectOption | null
selectedFlags: SelectOption[] | null
hookParameters: HookParameters
memos: Memos
txIsLoading: boolean
txIsDisabled: boolean
txFields: TxFields
viewType: 'json' | 'ui'
editorValue?: string
editorIsSaved: boolean
estimatedFee?: string
}
@@ -40,9 +50,10 @@ export type TxFields = Omit<
export const defaultTransaction: TransactionState = {
selectedTransaction: null,
selectedAccount: null,
selectedDestAccount: null,
selectedFlags: null,
hookParameters: {},
memos: {},
editorIsSaved: true,
txIsLoading: false,
txIsDisabled: false,
txFields: {},
@@ -118,46 +129,51 @@ export const modifyTxState = (
return tx.state
}
// state to tx options
export const prepareTransaction = (data: any) => {
let options = { ...data }
Object.keys(options).forEach(field => {
let _value = options[field]
// convert xrp
if (_value && typeof _value === 'object' && _value.$type === 'xrp') {
if (+_value.$value) {
options[field] = (+_value.$value * 1000000 + '') as any
if (!typeIs(_value, 'object')) return
// amount.xrp
if (_value.$type === 'amount.xrp') {
if (_value.$value) {
options[field] = (+(_value as any).$value * 1000000 + '')
} else {
options[field] = undefined // 👇 💀
options[field] = ""
}
}
// handle type: `json`
if (_value && typeof _value === 'object' && _value.$type === 'json') {
if (typeof _value.$value === 'object') {
// amount.token
if (_value.$type === 'amount.token') {
if (typeIs(_value.$value, 'string')) {
options[field] = parseJSON(_value.$value)
} else if (typeIs(_value.$value, 'object')) {
options[field] = _value.$value
} else {
try {
options[field] = JSON.parse(_value.$value)
} catch (error) {
const message = `Input error for json field '${field}': ${error instanceof Error ? error.message : ''
}`
console.error(message)
options[field] = _value.$value
options[field] = undefined
}
}
// account
if (_value.$type === 'account') {
options[field] = (_value.$value as any)?.toString() || ""
}
// json
if (_value.$type === 'json') {
const val = _value.$value;
let res: any = val;
if (typeIs(val, ["object", "array"])) {
options[field] = res
} else if (typeIs(val, "string") && (res = parseJSON(val))) {
options[field] = res;
} else {
options[field] = res;
}
// delete unnecessary fields
if (!options[field]) {
delete options[field]
}
})
return options
}
// editor value to state
export const prepareState = (value: string, transactionType?: string) => {
const options = parseJSON(value)
if (!options) {
@@ -167,7 +183,7 @@ export const prepareState = (value: string, transactionType?: string) => {
return
}
const { Account, TransactionType, Destination, HookParameters, ...rest } = options
const { Account, TransactionType, HookParameters, Memos, ...rest } = options
let tx: Partial<TransactionState> = {}
const schema = getTxFields(transactionType)
@@ -199,31 +215,21 @@ export const prepareState = (value: string, transactionType?: string) => {
if (HookParameters && HookParameters instanceof Array) {
tx.hookParameters = HookParameters.reduce<TransactionState["hookParameters"]>((acc, cur, idx) => {
const param = { label: fromHex(cur.HookParameter?.HookParameterName || ""), value: fromHex(cur.HookParameter?.HookParameterValue || "") }
const param = { label: fromHex(cur.HookParameter?.HookParameterName || ""), value: cur.HookParameter?.HookParameterValue || "" }
acc[idx] = param;
return acc;
}, {})
}
if (schema.Destination !== undefined) {
const dest = state.accounts.find(acc => acc.address === Destination)
if (dest) {
tx.selectedDestAccount = {
label: dest.name,
value: dest.address
}
} else if (Destination) {
tx.selectedDestAccount = {
label: Destination,
value: Destination
}
} else {
tx.selectedDestAccount = null
}
} else if (Destination) {
rest.Destination = Destination
if (Memos && Memos instanceof Array) {
tx.memos = Memos.reduce<TransactionState["memos"]>((acc, cur, idx) => {
const memo = { data: cur.Memo?.MemoData || "", type: fromHex(cur.Memo?.MemoType || ""), format: fromHex(cur.Memo?.MemoFormat || "") }
acc[idx] = memo;
return acc;
}, {})
}
if (getFlags(TransactionType) && rest.Flags) {
const flags = extractFlags(TransactionType, rest.Flags)
@@ -234,17 +240,31 @@ export const prepareState = (value: string, transactionType?: string) => {
Object.keys(rest).forEach(field => {
const value = rest[field]
const schemaVal = schema[field as keyof TxFields]
const isXrp =
typeof value !== 'object' &&
schemaVal &&
typeof schemaVal === 'object' &&
schemaVal.$type === 'xrp'
if (isXrp) {
const isAmount = schemaVal &&
typeIs(schemaVal, "object") &&
schemaVal.$type.startsWith('amount.');
const isAccount = schemaVal &&
typeIs(schemaVal, "object") &&
schemaVal.$type.startsWith("account");
if (isAmount && ["number", "string"].includes(typeof value)) {
rest[field] = {
$type: 'xrp',
$type: 'amount.xrp', // TODO narrow typed $type.
$value: +value / 1000000 // ! maybe use bigint?
}
} else if (typeof value === 'object') {
} else if (isAmount && typeof value === 'object') {
rest[field] = {
$type: 'amount.token',
$value: value
}
} else if (isAccount) {
rest[field] = {
$type: "account",
$value: value?.toString() || ""
}
}
else if (typeof value === 'object') {
rest[field] = {
$type: 'json',
$value: value
@@ -253,6 +273,7 @@ export const prepareState = (value: string, transactionType?: string) => {
})
tx.txFields = rest
tx.editorIsSaved = true;
return tx
}

31
utils/accountInfo.ts Normal file
View File

@@ -0,0 +1,31 @@
import toast from 'react-hot-toast'
import { xrplSend } from '../state/actions/xrpl-client'
interface AccountInfo {
Account: string,
Sequence: number,
Flags: number,
Balance?: string,
}
const fetchAccountInfo = async (
address: string,
opts: { silent?: boolean } = {}
): Promise<AccountInfo | undefined> => {
try {
const res = await xrplSend({
id: `hooks-builder-req-info-${address}`,
command: 'account_info',
account: address
})
return res.account_data;
} catch (err) {
if (!opts.silent) {
console.error(err)
toast.error('Could not fetch account info!')
}
}
}
export default fetchAccountInfo

View File

@@ -24,6 +24,9 @@ const estimateFee = async (
const { signedTransaction } = sign(copyTx, keypair)
const res = await xrplSend({ command: 'fee', tx_blob: signedTransaction })
if (res.error) {
throw new Error(`[${res.error}] ${res.error_exception}.`);
}
if (res && res.drops) {
return res.drops
}
@@ -31,7 +34,8 @@ const estimateFee = async (
} catch (err) {
if (!opts.silent) {
console.error(err)
toast.error('Cannot estimate fee.') // ? Some better msg
const msg = err instanceof Error ? err.message : 'Error estimating fee!';
toast.error(msg);
}
return null
}

View File

@@ -19,3 +19,23 @@ export const getFileExtention = (filename?: string): string | undefined => {
const ext = (filename.includes('.') && filename.split('.').pop()) || undefined
return ext
}
export const getFileNamePart = (filename?: string): string | undefined => {
if (!filename) return
const name = (filename.includes('.') && filename.split('.').slice(0, -1).join(".")) || filename
return name
}
type Type = "array" | "undefined" | "object" | "string" | "number" | "bigint" | "boolean" | "symbol" | "function"
type obj = Record<string | number | symbol, unknown>
type arr = unknown[]
export const typeIs = <T extends Type>(arg: any, t: T | T[]): arg is unknown & (T extends "array" ? arr : T extends "undefined" ? undefined | null : T extends "object" ? obj : T extends "string" ? string : T extends "number" ? number : T extends "bigint" ? bigint : T extends "boolean" ? boolean : T extends "symbol" ? symbol : T extends "function" ? Function : never) => {
const types = Array.isArray(t) ? t : [t]
return types.includes(typeOf(arg) as T);
}
export const typeOf = (arg: any): Type => {
const type = arg instanceof Array ? 'array' : arg === null ? 'undefined' : typeof arg
return type;
}

View File

@@ -30,7 +30,7 @@ export const tts = {
export type TTS = typeof tts
const calculateHookOn = (arr: (keyof TTS)[]) => {
let s = '0x3e3ff5bf'
let s = '0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffbfffff'
arr.forEach(n => {
let v = BigInt(s)
v ^= BigInt(1) << BigInt(tts[n])

View File

@@ -1,9 +1,8 @@
import { typeIs, typeOf } from './helpers'
export const extractSchemaProps = <O extends object>(obj: O) =>
Object.entries(obj).reduce((prev, [key, val]) => {
const typeOf = <T>(arg: T) =>
arg instanceof Array ? 'array' : arg === null ? 'undefined' : typeof arg
const value = typeOf(val) === 'object' && '$type' in val && '$value' in val ? val?.$value : val
const value = typeIs(val, "object") && '$type' in val && '$value' in val ? val?.$value : val
const type = typeOf(value)
let schema: any = {
@@ -12,19 +11,19 @@ export const extractSchemaProps = <O extends object>(obj: O) =>
default: value
}
if (typeOf(value) === 'array') {
if (typeIs(value, "array")) {
const item = value[0] // TODO merge other item schema's into one
if (typeOf(item) !== 'object') {
if (typeIs(item, "object")) {
schema.items = {
type: 'object',
properties: extractSchemaProps(item),
default: item
}
}
// TODO support primitive-value arrays
// TODO primitive-value arrays
}
if (typeOf(value) === 'object') {
if (typeIs(value, "object")) {
schema.properties = extractSchemaProps(value)
}
return {

View File

@@ -20,6 +20,13 @@ export type SetHookData = {
}
$metaData?: any
}[]
Memos?: {
Memo: {
MemoType: string,
MemoData: string
MemoFormat: string
}
}[]
// HookGrants: {
// HookGrant: {
// Authorize: string;
@@ -78,7 +85,8 @@ export const getInvokeOptions = (content?: string) => {
export function toHex(str: string) {
var result = ''
for (var i = 0; i < str.length; i++) {
result += str.charCodeAt(i).toString(16)
const hex = str.charCodeAt(i).toString(16)
result += hex.padStart(2, '0')
}
return result.toUpperCase()
}

1374
yarn.lock

File diff suppressed because it is too large Load Diff