Caigo - Golang Library for StarkNet/Cairo

Related tags

DevOps Tools caigo

Golang Library for StarkNet/Cairo

Go Reference

Caigo is predominately a transcription of the following libraries:



Although the library adheres to the 'elliptic/curve' interface. All testing has been done against library function explicity. It is recommended to use in the same way(i.e. curve.Sign and not ecdsa.Sign).

package main

import (


func main() {
	// NOTE: when not given local file path this pulls the curve data from Starkware github repo
	curve, err := caigo.SCWithConstants("")
	if err != nil {

	hash, err := curve.PedersenHash([]*big.Int{caigo.HexToBN("0x12773"), caigo.HexToBN("0x872362")})
	if err != nil {

	priv := curve.GetRandomPrivateKey()

	x, y, err := curve.PrivateToPoint(priv)
	if err != nil {

	r, s, err := curve.Sign(hash, priv)
	if err != nil {

	if curve.Verify(hash, r, s, x, y) {
		fmt.Println("signature is valid")
	} else {
		fmt.Println("signature is invalid")


goos: darwin
goarch: amd64
cpu: Intel(R) Core(TM) i7-9750H CPU @ 2.60GHz
BenchmarkSignatureVerify/sign_input_size_249-12                 1000000000               0.002313 ns/op
BenchmarkSignatureVerify/verify_input_size_249-12               1000000000               0.006192 ns/op
BenchmarkPedersenHash/input_size_17_24-12                       1000000000               0.0001771 ns/op
BenchmarkPedersenHash/input_size_37_48-12                       1000000000               0.0002878 ns/op
BenchmarkPedersenHash/input_size_37_160-12                      1000000000               0.0006268 ns/op
BenchmarkPedersenHash/input_size_160_48-12                      1000000000               0.0008042 ns/op
BenchmarkPedersenHash/input_size_160_160-12                     1000000000               0.001161 ns/op
BenchmarkPedersenHash/input_size_251_249-12                     1000000000               0.001569 ns/op
BenchmarkPedersenHash/input_size_251_251-12                     1000000000               0.001523 ns/op
BenchmarkGetMessageHash/input_size_160-12                       1000000000               0.02341 ns/op


go test -v
=== RUN   TestBadSignature
--- PASS: TestBadSignature (0.06s)
=== RUN   TestKnownSignature
--- PASS: TestKnownSignature (0.02s)
=== RUN   TestDerivedSignature
--- PASS: TestDerivedSignature (0.01s)
=== RUN   TestTransactionHash
--- PASS: TestTransactionHash (0.02s)
=== RUN   TestVerifySignature
--- PASS: TestVerifySignature (0.01s)
=== RUN   TestUIVerifySignature
--- PASS: TestUIVerifySignature (0.02s)
=== RUN   TestPedersenHash
--- PASS: TestPedersenHash (0.00s)
=== RUN   TestInitCurveWithConstants
--- PASS: TestInitCurveWithConstants (0.01s)
=== RUN   TestDivMod
--- PASS: TestDivMod (0.00s)
=== RUN   TestEcMult
--- PASS: TestEcMult (0.00s)
=== RUN   TestAdd
--- PASS: TestAdd (0.00s)
=== RUN   TestMultAir
--- PASS: TestMultAir (0.00s)
=== RUN   TestGetY
--- PASS: TestGetY (0.00s)
ok   0.454s


If you find an issue/bug or have a feature request please submit an issue here Issues


If you are looking to contribute, please head to the Contributing section.

  • proposal reduce the api surface

    proposal reduce the api surface


    I do not expect you accept that PR. It provides a few examples to continue the talk. Maybe that would be better to coordinate on the starkware discord. I could not DM you. Anyway, long story short, a few proposal:

    1. SNValToBN is actually almost the same as (i *big.Int{}).SetString(z, 0). The 0 for 2nd parameter checks for 0x and does a .SetString(z, 16) if it has one: If it does not... It works. I've added the change and a test to show it.
    2. There is a concern with not checking the value is correct with SNValToBN. If it is in the test or to interact with some backend it is probably okay (though as an oddity keys in pathfinder starknet_getEvents is actually an hexa without 0x in 0.2.2-alpha). However if you expose the conversion in an API, if could lead to the value being nil and the API panicking, i.e. a DDoS.
    3. You can probably remove all the HexToBN and StrToBig and replace them with SNValToBN. That would remove utilities and simplify the godoc.
    4. Another proposal is simply to not expose SNValToBN by renaming it snValToBN. It would only require a few changes since, except for the example, there is almost no conversion
    5. I also propose to remove the replace of the go.mod in your example with the go workspace clause because you already have set the environment to 1.18.
    opened by gregoryguillou 8
  • introduce support for RPC v0.2.1

    introduce support for RPC v0.2.1

    see #174 . This PR:

    • adds a v0.2.1 RPC implementation. Noone is using it
    • does some cleaning of v0.1.0 RPC and remove the contracts from the directory
    • adds a Github Action with devnet 0.3.5 to test the new implementation
    • changes the version format from an uint64 to a *big.Int to support format used to run EstimateFee
    opened by gregoryguillou 7
  • TestLocalStarkNet 403: unknown_error_format

    TestLocalStarkNet 403: unknown_error_format

    I'm observing that local starknet tests fail. Is it possible there are additional setup instructions needed in the README?

    === RUN   TestLocalStarkNet
        starknet_test.go:86: Could not deploy contract: 403: unknown_error_format
        starknet_test.go:91: Could not get tx: 403: unknown_error_format
        starknet_test.go:96: Could not get tx receipt: 403: unknown_error_format
        starknet_test.go:101: Could not get block by hash: 403: unknown_error_format
        starknet_test.go:106: Could not get storage: 403: unknown_error_format
    --- FAIL: TestLocalStarkNet (1.55s)
    opened by rootulp 7
  • Should Field `ChainId` in `Domain` be `*big.Int` or `string` instead of `int`?

    Should Field `ChainId` in `Domain` be `*big.Int` or `string` instead of `int`?

    Hello, everyone. I am building a TypedData in order to call GetMessageHash and generate a hash based on this data and an account address.

    However, the field ChainId in Domain is an int:

    type Domain struct {
    	Name    string
    	Version string
    	ChainId int

    Shouldn't it be *big.Int?

    The reason is that the currently Starknet/Starkware values for the Mainnet/Testnet are as follows:

    • Testnet (SN_GOERLI): 1536727068981429685321 or 0x534e5f474f45524c49
    • Mainnet (SN_MAIN): 23448594291968334 or 0x534e5f4d41494e

    These values overflow an int. Testnet and Mainnet are 71 bits and 55 bits long respectively. How can I build a well-formed TypedData.Domain with the proper values for ChainId ?

    opened by phramos07 5
  • issue with Uint256 type and/or SplitFactStr

    issue with Uint256 type and/or SplitFactStr

    I'm using Uint256 for ERC721 with Starknet and there is no direct support for that type in caigo. I do not know if that is something I should/could add, considering I'm also an adept of less is better. Uint256 is actually defined in the abi, maybe having an abigen as referenced in #1 would work better.

    In the meantime, I am using SplitFactStr to convert the Uint256 into 2 Felt. I would like for the function to work even when the strings are shorter than 32-bytes. I've written a PR with the test that with the current code and succeed with the change. Can you review the PR and provide some feedback?

    Thank you for the project!

    opened by gregoryguillou 4
  • Bug: RPC Account WaitForTransaction never ends if transaction fails due to missing fees

    Bug: RPC Account WaitForTransaction never ends if transaction fails due to missing fees

    I attempted to submit a transaction in the following two scenarios:

    1. Fee added to execute payload but not enough balance -> Resulted in WaitForTransaction never-ending
    2. No fee added to execute payload -> Resulted in WaitForTransaction never-ending

    I was only able to figure out this was the issue as Starkscan shows when a TX is rejected due to no fee

    Voyager doesn't present this information.

    If Starkscan is able to programmatically catch this scenario, then I'm sure there must be modifications we can make to Caigo to do the same.

    opened by rzmahmood 3
  • provide support for new Goerli2 chain ID SN_GOERLI2 in gateway provider

    provide support for new Goerli2 chain ID SN_GOERLI2 in gateway provider

    Following the upgrade of the StarkNet testnets today, the Goerli2 network has a new chain ID SN_GOERLI2. This pull request allows caigo clients to connect to accounts deployed on Goerli2.

    Prior to the StarkNet upgrade a caigo client could connect to Goerli2 as follows:

     gw := gateway.NewProvider(gateway.WithBaseURL(""))
     account, err := caigo.NewGatewayAccount(<account private key>, <account address>, gw, caigo.AccountVersion1)

    But since the upgrade the returned account has all transactions rejected with the message “Signature (…, …), is invalid, with respect to the public key …, and the message hash …”.

    With this pull request clients can successfully connect as follows:

     gw := gateway.NewProvider(gateway.WithChain("SN_GOERLI2"))
     account, err := caigo.NewGatewayAccount(<account private key>, <account address>, gw, caigo.AccountVersion1)

    Passing any string which contains "goerli2" in either upper or lower case as the chain ID will work.

    opened by alex-sumner 2
  • EC multiplication constant time

    EC multiplication constant time

    Hi folks! Thanks for the SDK, we're using it at Chainlink.

    During our analysis we found an issue with the EC Multiplication algorithm.

    Caigo’s PrivateToPoint function will multiply the curve generator by the private key scalar, obtaining the public key point. This function is not-constant time and could enable an attacker with knowledge about the timing of key generation to recover the private key. This information leakage will also be present in other side channels such as electromagnetic emanations or CPU temperature. Figure shows a plot of how long the PrivateToPoint function takes depending on the number of set bits on the private scalar:

    Screenshot 2022-10-28 at 10 19 32

    Exploit Scenario

    An attacker gets access to a side-channel on the computer running the GenerateKey function and obtains enough information to recover the private key.


    Use a constant time algorithm for scalar multiplication exposed via the PrivateToPoint function. Fix the upper bound on the private scalar sampling.

    This is a high difficulty exploit scenario, but we'd still love to patch this before moving to production.

    This PR implements the Double-And-Always-Add algorithm which should bring ~10x improvements over the original Double-And-Add implementation, measured as standard deviation when timing the PrivateToPoint function on keys (ec multiplication scalars) with 1 to 251 bits set.

    To verify run the the benchmark test where we test multiple different implementations:

    $ go test -bench BenchmarkEcMultAll -run=^$
    algo=       Double-And-Add
      mean=     1.0868900971390551e+06
      variance= 1.9250450004438724e+11
      std-dev=  438753.34761616035
    algo=       Double-And-Always-Add
      mean=     1.595599511976048e+06
      variance= 2.1961769142645793e+09
      std-dev=  46863.385646628  // ~10x IMPROVEMENT
    algo=       Montgomery-Ladder
      mean=     1.469757121756487e+06
      variance= 2.8182458667915974e+10
      std-dev=  167876.31955673787 // ~2,5x IMPROVEMENT
    algo=       Montgomery-Ladder-Lsh
      mean=     1.4823170239520958e+06
      variance= 2.667844449605206e+10
      std-dev=  163335.37429489076 // ~2,5x IMPROVEMENT

    This PR also brings the fuzz test and adds one signature verification test found in original implementaiton by Starkware here: starkware-libs/crypto-cpp


    opened by krebernisak 2
  • improve types and account management

    improve types and account management

    This PR is a refactor. In includes the following changes:

    • Accounts are now shared between the Gateway and RPC implementations. They have been moved up into the caigo directory.
    • Plugin support has been added to the session key and both implementation
    • Types when shared like FunctionCall have been moved up into the caigo/types directory.
    • Implementation specific inner types have been introduced with MarshalJSON/UnmarshalJSON. They are supposed to implement specificities from the API like the fact calldata should be base10 on the gateway
    • rpc/types directory has been removed as it should not be used by any higher level package.
    • rpc has been renamed rpcv01 has the type system will have to be rewritten and we want to prepare for the yet to come rpcv02
    • accounts proposes to install and demonstrate the session key with a v0 account.
    • accounts proposes to install v1 and v0 accounts and demonstrates the addInvokeTransaction (i.e. account.Execute`) with the 2 protocol versions
    • test provides now facilities for the devnet as requested by
    opened by gregoryguillou 2
  • Feature: Add Support for Devnet Mint and Mint Lite

    Feature: Add Support for Devnet Mint and Mint Lite

    The Shardlabs devnet allows for minting to an address using the local faucet ->

    This is necessary when the deployed and funded accounts are not sufficient (e.g. wrong account contract).

    It would be great to start adding support for devnet-specific functionality such as this.

    opened by rzmahmood 2
  • Uint256 Examples Ignores 'High' field

    Uint256 Examples Ignores 'High' field

    Not sure if Caigo maintainers here but the example given in Caigo for balanceOf ignores the 'high' result for Uint256. See This is not a good idea as the high field could have a value. In JS, Immutable X does it like this

    I'll look into making a PR if I have a capacity.

    opened by rzmahmood 2
  • Plans for adding support for signTypedData/signMessage

    Plans for adding support for signTypedData/signMessage

    👋 I'm David from ImmutableX, while we are planning to support StarkNet for ImmutableX's multi-rollup Orderbook, we noticed that off-chain signing & verification is a hard dependency. Although these features are already supported in other languages like JS & Cairo I see that Caigo seems to only support the basic Account.Sign() as of now.

    Do you have any plans to support this in the near future? This seems to be a need for many other projects as well since this is a frequently used functionality.

    Also, does anyone know any case or example/implementation of signTypedData or signMessage in Golang?

    opened by PowerStream3604 2
  • Support for RPC v0.2

    Support for RPC v0.2

    I tried using v0.1 but starknet-devnet only implements v0.2. The biggest difference seems to be starknet_getNonce and a couple other methods now also take an additional block_id parameter.

    opened by archseer 3
  • chore: extract curve to separate package

    chore: extract curve to separate package

    a quick and dirty example of how we can improve the curve apis. with this approach the curve is initialized a single time and helpers are all plain functions.

    opened by tarrencev 1
  • Move the interface to Felt

    Move the interface to Felt

    I am handling over that PR that @internnos has written. Thank to him! I will detail the content of what I am changing here. It seems we are stuck on a test but since there is also an issue with Pathfinder 0.3.0-alpha breaking the interface it might also come from there. Below are the list of my findings:

    There are a LOT of breaking changes. btw, @drspacemn I would not go for 1.0 before the protocol ossifies. Right now we have seen they continue to introduce breaking changes in the payload and also it the api. For instance Pathfinder has removed get_code.

    • Transaction is used to get data in and out. We used to rely on that fact to enter the entrypoint as a string (i.e. the name of the function) and return in the same data the keccak256 & (252-1) of the function. We cannot do that anymore. What I have done is turn it into a Felt we will have to inject the entrypoint. The reason I did that it that I understand the entrypoint will be removed when calling an account because it will call both __execute__ and __validate__ and whatever the name of the function will be to handle the commit to pay.
    • BlockNumber where not consistent accross the stack. I moved them to uint64, not that I am proud of it but at least to have something consistent
    • Thinking about it: (1) the curve implementation should be with the Felt implementation and (2) the account should not have a private field but a signer attached to it because it could very well be that the signer authentication does rely on a key that has a different scheme than secp256k1. For now I will leave it that way
    opened by gregoryguillou 0
  • add mock tests for the whole JSON RPC API

    add mock tests for the whole JSON RPC API


    The JSON RPC API is well implemented. However, not all the routes have their dedicated tests. Make sure we implement those tests with a mock to ease the test process.

    Acceptance criteria

    • [ ] every API call from the rpc directory should be implemented with a mock

    Additional Notes

    #78 should be addressed first to make sure we correctly capture the payload

    Type: test Techno: golang Difficulty: easy Duration: under a day State: blocked 
    opened by gregoryguillou 0
  • v0.4.1(Oct 24, 2022)

    this is a preview of go-starknet, the caigo cli to work with Starknet.

    if you have Go 1.18+ installed

    go install
    go-starknet help

    on MacOS with Homebrew

    brew tap dontpanicdao/dontpanicdao
    brew install go-starknet
    go-starknet help
    Source code(tar.gz)
    Source code(zip)
    checksums.txt(518 bytes)
    go-starknet_0.4.1_darwin_arm64.tar.gz(2.89 MB)
    go-starknet_0.4.1_darwin_x86_64.tar.gz(3.01 MB)
    go-starknet_0.4.1_linux_arm64.tar.gz(2.66 MB)
    go-starknet_0.4.1_linux_i386.tar.gz(2.79 MB)
    go-starknet_0.4.1_linux_x86_64.tar.gz(2.90 MB)
  • v0.4.0(Oct 23, 2022)

    This release breaks many of the 0.3.x API to support the gateway and the rpc v0.1 protocol together. It is being tested against starknet-devnet, eqlabs/pathfinder and the standard starknet gateway. It includes the following:

    • support for Starknet v0.10.1 protocol on the gateway
    • support for Starknet v0.10.0 protocol on the rpc v0.1 because it is not compatible with the latest release
    • support for both V0 and V1 accounts for invoke transaction
    • an account manager to install many account versions, including the plugin account and the openzeppelin accounts
    • an account interface and the associated implementation for both the gateway and rpc v0.1
    • support for plugin extensions in the account and an implementation of the session key.
    • some tools to work with devnet and transform help with converting data
    • an implementation of a fixed-size merkle tree algorithm

    known issues: due to the fact rpc v0.2 is not yet fully supported by Pathfinder and Devnet, the implementation is lacking. It remains a short term goal to implement it. Hopefully it will be part of v0.5.0.

    Source code(tar.gz)
    Source code(zip)
  • v0.3.1(Sep 8, 2022)


    • nodes have ammended their starknet_getEvents params interface from ..."fromBlock": 800 ... to ..."fromBlock": {"block_number": 250000}... in order to support both block_number and block_hash values
    • addresses these changes


    • in order for this release to still access blocks from we've added a BlockWithTxs utility function
    • please note BlockWithTxHashes and other RPC v0.2.0 functionality will be added in the caigo v0.4.0 release
    Source code(tar.gz)
    Source code(zip)
  • v0.3.0(Jun 28, 2022)

    Gateway Package:

    • Starknet client/provider implementation for feeder and gateway apis
    • Endpoints/Types including: estimate_fee, get_block, get_block_hash_by_id, get_id_by_hash, get_class_by_hash, get_class_hash_at, get_full_contract, call_contract, add_transaction, get_state_update, get_contract_addresses, get_storage_at, get_transaction, get_transaction_status, get_transaction_id_by_hash, get_transaction_receipt, get_transaction_trace

    RPC Package:

    • RPC client implementing StarkNet RPC Spec
    • Method implementation status included in README

    Types Package:

    • Common provider types
    • Post v0.3.0 *big.Int args/returns will be changed to *types.Felts

    StarkNet v0.9.0 Support:

    • provider getters for class hashes and definitions
    • estimate fee getters for transaction type
    • Accounts with signature schemes adhering to SN get_tx_info -> tx.hash
    • Accounts compatible w/ Argent v0.9.0
    • NOTE: devnet uses preloaded accounts based on OZ v0.1.0 and signatures are incompatible with caigo Accounts
    Source code(tar.gz)
    Source code(zip)
  • v0.2.0(Apr 1, 2022)

    Support for StarkNet actions:

    • Gateway and Signer structures(similar to starknet.js)
    • Setters - Deploy, invoke, execute transactions on StarkNet contracts(support for OpenZeppelin Account Multicall)
    • Getters - transaction, transaction status, transaction receipt, storage, code, block
    • Feeder Gateway poller for desired transaction status
    • Contract call - post calldata to contract at desired entry point
    • Typed Data and an encoding interface


    • proper randomness generation for private
    • proper curve boundary checking
    Source code(tar.gz)
    Source code(zip)
  • v0.1.0(Jan 10, 2022)

    Implements the crypto primitives for initiating and using various StarkNet functionality:

    • Sign Message
    • Verify Signature
    • Hash array of elements
    • Obtain Pedersen hash of elements
    • Parse and hash starknet transaction in accordance with 'starknet.js'
    • Initialize the Starknet Elliptic Curve
    • Initialize the Starknet Elliptic Curve w/ Constant Points
    • Elliptic Curve math primitives: Add, Double, DivMod, InvMod, EcMult, ScalarMult, ScalarBaseMult, MimicEcMultAir
    Source code(tar.gz)
    Source code(zip)
Don't Panic DAO
A DAO that ships
Don't Panic DAO
A Golang library for testing infrastructure in automated ways.

Infratest Infratest is a Golang library that we hope makes testing your infrastructure using tests that are written in Golang easier to do. The genera

HBO Digital Products 16 Nov 2, 2022
The community-supported Golang library for Vonage

Vonage Go SDK This is the community-supported Golang library for Vonage. It has support for most of our APIs, but is still under active development. I

null 1 Dec 1, 2021
library for working with github api, written in Golang

gitdata library for working with github api, written in Golang Example: get user data package main import ( "fmt" "log" "

Aleksandr Rudenko 1 May 19, 2022
A library for writing backup programs in Golang

Barkup Barkup is a library for backing things up. It provides tools for writing bare-bones backup programs in Go. T

Kyle Truscott 212 Nov 13, 2022
A go (golang) library to search videos in YouTube.

YT Search A go (golang) library to search videos in YouTube. Installation go get Usage package main import ( "fmt"

Anjana Madu 4 Oct 1, 2022
Using the Golang search the Marvel Characters. This project is a web based golang application that shows the information of superheroes using Marvel api.

marvel-universe-web using the Golang search the Marvel Universe Characters About The Project This project is a web based golang application that shows

Burak KÖSE 2 Oct 10, 2021
Golang-tutorials - This repository contains golang tutorials right from basic to advanced.

Golang-tutorials This repository contains golang tutorials right from basic to advanced. Go is a statically typed, compiled programming language desig

Prayas Gautam 0 Jan 3, 2022
Golang-for-node-devs - Golang for Node.js developers

Golang for Node.js developers Who is this video for? Familiar with Node.js and i

TomDoesTech 6 Dec 7, 2022
Poc rsa - A simple golang scaffolding to help me to create new api projects or workers with golang on k8s

go-scaffold A simple golang scaffolding to help me to create new api projects or

André Luis 0 Feb 3, 2022
Golang-samples - Help someone need some practices when learning golang

GO Language Samples This project is to help someone need some practices when lea

Gui Chen 1 Jan 11, 2022
HTTP load testing tool and library. It's over 9000!

Vegeta Vegeta is a versatile HTTP load testing tool built out of a need to drill HTTP services with a constant request rate. It can be used both as a

Tomás Senart 20.6k Dec 30, 2022
Go library to create resilient feedback loop/control controllers.

Gontroller A Go library to create feedback loop/control controllers, or in other words... a Go library to create controllers without Kubernetes resour

Spotahome 149 Jan 1, 2023
Orchestra is a library to manage long running go processes.

Orchestra Orchestra is a library to manage long running go processes. At the heart of the library is an interface called Player // Player is a long ru

Stephen Afam-Osemene 111 Oct 21, 2022
Automated configuration documentation library for Go Projects.

Cato Cato is an automated documentation generation library for Go Projects. Through the use of custom tags for struct fields, Cato can extract informa

CS3 Organization 6 Aug 28, 2020
Gohalt 👮‍♀🛑: Fast; Simple; Powerful; Go Throttler library

Gohalt ??‍♀ ?? : Fast; Simple; Powerful; Go Throttler library go get -u Introduction Gohalt is simple and convenient yet powerf

Kostiantyn Masliuk 257 Nov 27, 2022
A K8s ClusterIP HTTP monitoring library based on eBPF

Owlk8s Seamless RED monitoring of k8s ClusterIP HTTP services. This library provides RED (rate,error,duration) monitoring for all(by default but exclu

null 17 Jun 16, 2022
library to make building things with bitclout easy

cloutcli library to make building things with bitclout easy quick start demo cmd $ ./clout demo clout demo visualizegraph # make clout.gv graph fi

Andrew Arrow 18 Jul 27, 2022
A Go library for the Linux Landlock sandboxing feature

Go landlock library The Go landlock library provides an interface to Linux 5.13's Landlock kernel sandboxing features. The library provides access to

Günther Noack 77 Dec 27, 2022
A simple and flexible health check library for Go.

Health A simple and flexible health check library for Go. Documentation · Report Bug · Request Feature Table of Contents Getting started Synchronous v

Alexander Liesenfeld 637 Jan 4, 2023