algorand-devrel / community

11 stars 3 forks source link

SDKs - Provide API Schema return to object #19

Closed barnjamin closed 1 year ago

barnjamin commented 3 years ago

The state and state delta objects returned need to be decoded to be useful for a client, this is currently left up to the user of an SDK.

The SDKs should provide an easy way to marshal the state schema into some language specific object, taking care to decode to the correct types.

Here is my junky TS version but I've had a Go and Python custom implementation shared with me from community members. If we all have to write our own, it should probably be included in the SDKs

// Converts an array of global-state or global-state-deltas to a more
// friendly generic object
export function StateToObj(sd: State[]): Obj {
    const obj = {} as Obj

    // Start with empty set
    Object.values(StateKeys).forEach((k)=>{
        obj[k] = {i:0, b: new Uint8Array()}
    })

    for(const idx in sd){
        const key = Buffer.from(sd[idx].key, 'base64').toString()

        // https://github.com/algorand/go-algorand/blob/master/data/basics/teal.go
        // In both global-state and state deltas, 1 is bytes and 2 is int
        const v = sd[idx].value
        const dataTypeFlag = v.action?v.action:v.type
        switch(dataTypeFlag){
            case 1:
                obj[key] = {b:Buffer.from(v.bytes, 'base64'), i:0}
                break;
            case 2:
                obj[key] = {i:v.uint, b:new Uint8Array()}
                break;
            default: // ??
        }
    }

    return obj
}
barnjamin commented 1 year ago

This is available in beaker, beaker-ts, and the algokit utils repos