|
| 1 | +import { |
| 2 | + Address, |
| 3 | + nativeToScVal, |
| 4 | + scValToNative, |
| 5 | + StrKey, |
| 6 | + xdr, |
| 7 | +} from '@stellar/stellar-sdk'; |
| 8 | + |
| 9 | +/** Supported JavaScript input types for Soroban ScVal encoding. */ |
| 10 | +export type ScValJsInput = |
| 11 | + | boolean |
| 12 | + | number |
| 13 | + | bigint |
| 14 | + | string |
| 15 | + | Uint8Array |
| 16 | + | Buffer |
| 17 | + | null |
| 18 | + | ScValJsInput[] |
| 19 | + | Map<ScValJsInput, ScValJsInput> |
| 20 | + | Record<string, ScValJsInput> |
| 21 | + | { __type: string; value: unknown }; |
| 22 | + |
| 23 | +export interface ScValTypeHint { |
| 24 | + type: string; |
| 25 | + element?: ScValTypeHint; |
| 26 | + key?: ScValTypeHint; |
| 27 | + value?: ScValTypeHint; |
| 28 | +} |
| 29 | + |
| 30 | +export interface SerializationResult { |
| 31 | + scVal: xdr.ScVal; |
| 32 | + rawXdr: string; |
| 33 | + xdrType: string; |
| 34 | +} |
| 35 | + |
| 36 | +export interface RoundTripResult<T = unknown> { |
| 37 | + original: T; |
| 38 | + encoded: SerializationResult; |
| 39 | + decoded: unknown; |
| 40 | + matches: boolean; |
| 41 | +} |
| 42 | + |
| 43 | +const INTEGER_TYPES = new Set(['u32', 'i32', 'u64', 'i64', 'u128', 'i128', 'u256', 'i256']); |
| 44 | + |
| 45 | +/** Encodes a JavaScript value to an ScVal using an explicit type hint. */ |
| 46 | +export function jsToScVal(value: unknown, hint: ScValTypeHint): xdr.ScVal { |
| 47 | + if (hint.type === 'option') { |
| 48 | + if (value === null || value === undefined) { |
| 49 | + return xdr.ScVal.scvVoid(); |
| 50 | + } |
| 51 | + return jsToScVal(value, hint.element ?? { type: 'val' }); |
| 52 | + } |
| 53 | + |
| 54 | + if (INTEGER_TYPES.has(hint.type) && typeof value === 'number') { |
| 55 | + return nativeToScVal(BigInt(value), { type: hint.type as any }); |
| 56 | + } |
| 57 | + |
| 58 | + return nativeToScVal(value as any, hint as any); |
| 59 | +} |
| 60 | + |
| 61 | +/** Decodes an ScVal into a JSON-safe JavaScript value. */ |
| 62 | +export function scValToJs(scVal: xdr.ScVal): unknown { |
| 63 | + const native = scValToNative(scVal); |
| 64 | + return formatJsValue(native); |
| 65 | +} |
| 66 | + |
| 67 | +/** Converts native SDK values into JSON-safe representations. */ |
| 68 | +export function formatJsValue(value: unknown): unknown { |
| 69 | + if (typeof value === 'bigint') return value.toString(); |
| 70 | + if (value instanceof Uint8Array) return `0x${Buffer.from(value).toString('hex')}`; |
| 71 | + if (Array.isArray(value)) return value.map(formatJsValue); |
| 72 | + if (value instanceof Map) { |
| 73 | + const out: Record<string, unknown> = {}; |
| 74 | + for (const [key, entry] of value.entries()) { |
| 75 | + out[String(formatJsValue(key))] = formatJsValue(entry); |
| 76 | + } |
| 77 | + return out; |
| 78 | + } |
| 79 | + if (value && typeof value === 'object') { |
| 80 | + const out: Record<string, unknown> = {}; |
| 81 | + for (const [key, entry] of Object.entries(value as Record<string, unknown>)) { |
| 82 | + out[key] = formatJsValue(entry); |
| 83 | + } |
| 84 | + return out; |
| 85 | + } |
| 86 | + return value; |
| 87 | +} |
| 88 | + |
| 89 | +/** Serializes a value and returns the ScVal plus base64 XDR. */ |
| 90 | +export function serializeValue(value: unknown, hint: ScValTypeHint): SerializationResult { |
| 91 | + const scVal = jsToScVal(value, hint); |
| 92 | + return { |
| 93 | + scVal, |
| 94 | + rawXdr: scVal.toXDR('base64'), |
| 95 | + xdrType: scVal.switch().name, |
| 96 | + }; |
| 97 | +} |
| 98 | + |
| 99 | +/** Encodes then decodes a value and reports whether the round-trip matches. */ |
| 100 | +export function roundTrip<T>(value: T, hint: ScValTypeHint): RoundTripResult<T> { |
| 101 | + const encoded = serializeValue(value, hint); |
| 102 | + const decoded = scValToJs(encoded.scVal); |
| 103 | + const matches = stableStringify(decoded) === stableStringify(formatJsValue(value)); |
| 104 | + return { original: value, encoded, decoded, matches }; |
| 105 | +} |
| 106 | + |
| 107 | +/** Stable JSON comparison helper for round-trip checks. */ |
| 108 | +export function stableStringify(value: unknown): string { |
| 109 | + return JSON.stringify(value, (_key, current) => { |
| 110 | + if (typeof current === 'bigint') return current.toString(); |
| 111 | + if (current instanceof Uint8Array) return `0x${Buffer.from(current).toString('hex')}`; |
| 112 | + return current; |
| 113 | + }); |
| 114 | +} |
| 115 | + |
| 116 | +/** Encodes a Stellar address string to scvAddress. */ |
| 117 | +export function encodeAddress(value: string): xdr.ScVal { |
| 118 | + if (!StrKey.isValidEd25519PublicKey(value) && !StrKey.isValidContract(value)) { |
| 119 | + throw new TypeError(`Invalid Stellar address: ${value}`); |
| 120 | + } |
| 121 | + return Address.fromString(value).toScVal(); |
| 122 | +} |
| 123 | + |
| 124 | +/** Encodes nested map/vector structures from plain JS objects. */ |
| 125 | +export function encodeNested(value: Record<string, unknown>): xdr.ScVal { |
| 126 | + const entries = Object.entries(value).map(([key, entry]) => { |
| 127 | + if (typeof entry === 'boolean') { |
| 128 | + return new xdr.ScMapEntry({ key: xdr.ScVal.scvSymbol(key), val: xdr.ScVal.scvBool(entry) }); |
| 129 | + } |
| 130 | + if (typeof entry === 'number') { |
| 131 | + return new xdr.ScMapEntry({ key: xdr.ScVal.scvSymbol(key), val: xdr.ScVal.scvU32(entry) }); |
| 132 | + } |
| 133 | + if (typeof entry === 'string') { |
| 134 | + return new xdr.ScMapEntry({ key: xdr.ScVal.scvSymbol(key), val: xdr.ScVal.scvString(entry) }); |
| 135 | + } |
| 136 | + if (typeof entry === 'bigint') { |
| 137 | + return new xdr.ScMapEntry({ |
| 138 | + key: xdr.ScVal.scvSymbol(key), |
| 139 | + val: nativeToScVal(entry, { type: 'i128' }), |
| 140 | + }); |
| 141 | + } |
| 142 | + if (Array.isArray(entry)) { |
| 143 | + return new xdr.ScMapEntry({ |
| 144 | + key: xdr.ScVal.scvSymbol(key), |
| 145 | + val: nativeToScVal(entry, { type: 'vec', element: { type: 'u32' } }), |
| 146 | + }); |
| 147 | + } |
| 148 | + if (entry && typeof entry === 'object') { |
| 149 | + return new xdr.ScMapEntry({ |
| 150 | + key: xdr.ScVal.scvSymbol(key), |
| 151 | + val: encodeNested(entry as Record<string, unknown>), |
| 152 | + }); |
| 153 | + } |
| 154 | + throw new TypeError(`Unsupported nested value for key "${key}"`); |
| 155 | + }); |
| 156 | + |
| 157 | + return xdr.ScVal.scvMap(entries); |
| 158 | +} |
| 159 | + |
| 160 | +/** Returns a human-readable explanation when a JS type cannot be encoded. */ |
| 161 | +export function describeUnsupportedJsType(value: unknown): string { |
| 162 | + if (value === undefined) { |
| 163 | + return 'undefined is not encodable; use null with an Option<T> hint or omit the field.'; |
| 164 | + } |
| 165 | + if (typeof value === 'function') { |
| 166 | + return 'Functions cannot be encoded as ScVal.'; |
| 167 | + } |
| 168 | + if (value instanceof Date) { |
| 169 | + return 'Date objects are not supported; encode as a u64 timestamp or ISO string.'; |
| 170 | + } |
| 171 | + return `Type "${Object.prototype.toString.call(value)}" is not supported by nativeToScVal.`; |
| 172 | +} |
| 173 | + |
| 174 | +/** Attempts encoding and returns either a SerializationResult or an error message. */ |
| 175 | +export function trySerialize( |
| 176 | + value: unknown, |
| 177 | + hint: ScValTypeHint, |
| 178 | +): { ok: true; result: SerializationResult } | { ok: false; error: string } { |
| 179 | + try { |
| 180 | + return { ok: true, result: serializeValue(value, hint) }; |
| 181 | + } catch (error: any) { |
| 182 | + return { ok: false, error: error?.message || describeUnsupportedJsType(value) }; |
| 183 | + } |
| 184 | +} |
0 commit comments